在cdef类中混合cdef和常规python属性 [英] Mixing cdef and regular python attributes in cdef class

查看:103
本文介绍了在cdef类中混合cdef和常规python属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Cython,现在正在尝试。我尝试了基本的cdef类示例程序,并且效果很好。

i am learning Cython and now experimenting with it. I tried the basic cdef class sample program and it works perfectly.

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

Now what i want to do is have a mix of cdef and non cdef mix of attributes in the cdef class type, something like this

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

但是一旦实例化对象,我就会出错

but as soon as i instantiate the object i get error

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

这是否意味着一旦您定义了一个全自定义cdef的python类。 *必须定义cdef属性?

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

推荐答案


这是否意味着一旦您定义了python类, cdef必须将所有self。*属性定义为cdef?

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

是。 文档


cdef类中的属性的行为与常规类中的属性不同:

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


  • 所有属性必须在编译时预先声明

  • ...

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

You can quite happily store a string by defining the attribute to be of type object:

cdef public object msg






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


Internally, the reason for this is that the cdef class does not have a dictionary, which saves space and makes attribute access faster, but it does mean that it cannot have arbitrary attributes added at runtime. This is reasonably similar to using __slots__ in a normal Python class.

这篇关于在cdef类中混合cdef和常规python属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆