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

2019-07-28 18:18发布

问题:

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:

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.