Can a cdef class store a variable that isn’t (type

2019-07-28 17:54发布

I’m curious if the following is valid, where only some of the variables are type-declared in a type-declared class. That is, would cdef before the class be invalid in this case?

cdef class CythonClass:

    cdef int var1, var2

    def __init__(self, a, b):
        self.var1 = a
        self.var2 = b
        self.defaultdict = DefaultDict(DefaultDict([]))

1条回答
别忘想泡老子
2楼-- · 2019-07-28 18:26

Short answer:

No, you need to declare it. Otherwise, you'll get an AttributeError: 'xxx.CythonClass' object has no attribute 'defaultdict' error.

(slightly) longer answer:

You can always declare it as (python) object:

cdef class CythonClass(object):

    cdef int var1, var2
    cdef object defaultdict  # declared as python object

This won't be very efficient, but it works.

查看更多
登录 后发表回答