Python 用classmethod处理Cython中的单例

Python 用classmethod处理Cython中的单例,python,python-2.7,singleton,cython,Python,Python 2.7,Singleton,Cython,这是一个问题,下面是来自 当MyCythonClass没有任何要初始化的属性时,上述链接中的解决方案将起作用 如果我有cinit myCythonClass的属性,那么解决方案似乎不起作用 我是Cython和C的新手,非常感谢您的帮助 cdef class Singleton: _instances = {} @classmethod def instance(cls, *args, **kwargs): if cls not in cls._instan

这是一个问题,下面是来自

当MyCythonClass没有任何要初始化的属性时,上述链接中的解决方案将起作用

如果我有cinit 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)
回溯(最近一次呼叫最后一次):
文件“run_testing.py”,第3行,在
c=MyCythonClass()。实例(1,2)
文件“testing.pyx”,第12行,testing.MyCythonClass.\uu cinit__
def _; cinit ___;(自我、内部苹果、内部橙色):
TypeError:\uuuuCinit\uuuu()正好接受2个位置参数(给定0个)

您需要省略MyCythonClass后面的括号,并将参数传递给实例方法,即MyCythonClass.instance(1,2)。非常感谢,直到我问了一个非常愚蠢的问题,我不熟悉classmethod