擅长:python、mysql、java
<p>正如@DavidW所指出的,cdef类的问题是它们没有<code>__dict__</code>。如果确实需要,可以将<code>__dict__</code>添加到类定义中:</p>
<pre><code>%%cython
cdef class A:
cdef dict __dict__ # now the usual attribute look-up is possible
cdef readonly int answer
def __init__(self):
self.answer=42 #cdef attribute
self.question="unknown" #pure python attribute, possible
</code></pre>
<p>现在:</p>
^{pr2}$
<p>注意:如果<code>cdef class A</code>没有<code>__dict__</code>,而是用<code>cdef public object question</code>来定义,则<code>setattr(a,'new_attr', None)</code>是不可能的。在</p>
<p>显然,使用<code>__dict__</code>会有额外的成本,因此当性能重要时,可能会使用预定义的属性。在</p>
<p>另一种方法是创建<code>cdef class</code>的子类并使用它而不是基类。在</p>
<hr/>
<p>注意:<a href="https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#dynamic-attributes" rel="nofollow noreferrer">here is the part</a>在关于动态属性的Cython文档中。在</p>