Singleton in Cython handled by classmethod

2019-08-21 08:57发布

问题:

This is a question following by the answer from Singleton is not working in Cython

The solution from the above link works when MyCythonClass do not have any attritbute to be initialize.

The solution doesnt seem to be working if i have attributes to cinit my myCythonClass.

I am quite new to Cython and C, any help is appreciated.

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

Error:

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)