这是一个问题,后面是Singleton is not working in Cython的答案
当MyCythonClass没有要初始化的属性时,上述链接中的解决方案将起作用。
如果我具有初始化myCythonClass的属性,则该解决方案似乎无法正常工作。
我对Cython和C还是很陌生,感谢您的帮助。
cdef class Singleton:
_instances = {}
@classmethod
def instance(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = cls(*args, **kwargs)
return cls._instances[cls]
cdef class MyCythonClass(Singleton):
cdef int apple, orange
def __cinit__(self, int apple, int orange):
self.apple = apple
self.orange = orange
pass
c = MyCythonClass(1,2).instance()
d = MyCythonClass(3,4).instance()
e = c is d # True
print 'res=', e
错误:
Traceback (most recent call last):
File "run_testing.py", line 3, in <module>
c = MyCythonClass().instance(1,2)
File "testing.pyx", line 12, in testing.MyCythonClass.__cinit__
def __cinit__(self, int apple, int orange):
TypeError: __cinit__() takes exactly 2 positional arguments (0 given)