本文介绍了cdef类可以存储未声明(类型)的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很好奇以下内容是否有效,其中只有一些变量在类型声明的类中进行了类型声明.也就是说,在这种情况下,在类之前的cdef
是否无效?
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([]))
推荐答案
简短答案:
否,您需要声明它.否则,您会收到AttributeError: 'xxx.CythonClass' object has no attribute 'defaultdict'
错误.
您始终可以将其声明为(python)对象:
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.
这篇关于cdef类可以存储未声明(类型)的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!