Singleton in Cython handled by classmethod

孤人 提交于 2019-12-13 03:56:58

问题


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)

来源:https://stackoverflow.com/questions/51263233/singleton-in-cython-handled-by-classmethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!