Singleton在Cython不工作 [英] Singleton is not working in Cython

查看:98
本文介绍了Singleton在Cython不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我定义Singleton的方式。

This is how i define Singleton.

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

然后我定义了我的课程如:

Then I have my classes defined as:

class MyClass(object):
    __metaclass__ = Singleton

    def __init__(self):
        pass


a = MyClass()
b = MyClass()

a is b将返回True

"a is b" will return True

但是

cdef class MyCythonClass(object):
    __metaclass__ = Singleton

    def __cinit__(self):
        pass

c = MyCythonClass()
d = MyCythonClass()

c is d将返回False

"c is d" will return False

我认为这是正在运行的c代码(cinit)前init,所以我试图将cinit放回init,它也不起作用。
如果我在类之前删除了 cdef,问题就解决了。

I thought it is the c code (cinit) running before init and so I tried to put the cinit back to init, it doesnt work either. The problem is solved if i removed the "cdef" before "class"

我想知道为什么,可能我在这里错过了一些重要的东西。

I am wondering why, probably I am missing something important here. Your help would be much appreciated.

Win 10 / Python 2.7

Win 10 / Python 2.7

推荐答案

Cython似乎不支持现成的元类。但是此模块可能提供了一种解决方法。

Cython does not appear to support meta classes out of the box. But this module may provide a workaround.

如下所示实施单例可能是另一种(更安全的)选择:

Implementing the singleton as follows may be another (safer) alternative:

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):
    pass

c = MyCythonClass.instance()
d = MyCythonClass.instance()
c is d  # True

这篇关于Singleton在Cython不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆