sách gpt4 ăn đã đi

python - 在 cdef 类中混合 cdef 和常规 python 属性

In lại 作者:太空狗 更新时间:2023-10-29 22:12:31 25 4
mua khóa gpt4 giày nike

我正在学习 Cython,现在正在试验它。我尝试了基本的 cdef 类示例程序,它运行良好。

现在我想做的是在 cdef 类类型中混合使用 cdef 和非 cdef 属性,就像这样

cdef class Context:
cdef public int byteIndex, bitIndex

def __init__(self, msg = "", msg_len = 0):
self.msg = msg
self.msg_len = msg_len
self.byteIndex = 0
self.bitIndex = 7

但是一旦我实例化对象我就得到错误

!! AttributeError: 'c_asnbase.Context' 对象没有属性 'msg'

这是否意味着一旦您使用 cdef 定义了一个 python 类,所有 self.* 属性都必须被 cdef 定义?

câu trả lời hay nhất

Does this mean once you define a python class with cdef all self.* attributes have to be cdef defined?

是的。这在 the documentation 中有明确说明。 :

Attributes in cdef classes behave differently from attributes in regular classes:

  • All attributes must be pre-declared at compile-time
  • ...

您可以通过将属性定义为对象类型来非常愉快地存储字符串:

cdef public object msg

在内部,这样做的原因是cdef类没有字典,这样可以节省空间并使属性访问更快,但这确实意味着它不能在运行时添加任意属性。这与在普通 Python 类中使用 __slots__ 相当相似。

关于python - 在 cdef 类中混合 cdef 和常规 python 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632297/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress