gpt4 book ai didi

Cython 使用 cinit()

转载 作者:行者123 更新时间:2023-12-04 11:58:45 26 4
gpt4 key购买 nike

我有:

      cdef class BaseClass():
def __cinit__(self,char* name):
print "BaseClass __cinit__()"
#...
def __dealloc__():
print "BaseClass __dealloc__()"
#...
cdef class DerClass(BaseClass):
def __cinit__(self,char* name,int n):
print "DerClass __cinit__()"
#...
def __dealloc__():
print "DerClass __dealloc__()"
#...

当我在 cyhton 中调用 DerClass 时,会自动调用 BaseClass 的构造函数,它必须打印的是:
       BaseClass __cinit__()
DerClass __cinit__()
DerClass __dealloc__()
BaseClass __dealloc__()

但它没有,它崩溃了我称之为 DerClass('Ciao')的那些。
为什么会这样,我怎样才能避免调用 初始化 基类。
谢谢!

最佳答案

上面的答案可能不是最好的解决方案。阅读上面链接的“初始化方法:__cinit__() 和 __init__()”部分提供了以下信息:

If your extension type has a base type, the __cinit__() method of the base type is automatically called before your __cinit__() method is called; you cannot explicitly call the inherited __cinit__() method.





If you anticipate subclassing your extension type in Python, you may find it useful to give the __cinit__() method * and ** arguments so that it can accept and ignore extra arguments.



所以我的解决方案是替换 __cinit()__ 的参数在 BaseClass以便可以将可变数量的参数传递给任何派生类:
cdef class BaseClass:
def __cinit__(self, *argv):
print "BaseClass __cinit__()"
#...
def __dealloc__(self):
print "BaseClass __dealloc__()"
#...

cdef class DerClass(BaseClass):
def __cinit__(self,char* name, int n):
print "DerClass __cinit__()"
#...
def __dealloc__(self):
print "DerClass __dealloc__()"
#...

here *args 的解释python中的变量

关于Cython 使用 cinit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7675284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com