用元类实现单例 [英] implement singleton with metaclass
本文介绍了用元类实现单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码是我如何使用元类实现单例,并且效果很好
the code below is how i implement singleton with metaclass, and it works well
class Test_MetaClass(type):
def __init__(cls, name, bases, dict):
super(Test_MetaClass, cls).__init__(cls, bases, dict)
cls._instance = None
print 'Test_MetaClass __init__'
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Test_MetaClass, cls).__call__(*args, **kwargs)
print 'Test_MetaClass __call__'
return cls._instance
class A(object):
__metaclass__ = Test_MetaClass
def __init__(self):
print 'A __init__ triggered'
a = A()
b = A()
输出:
Test_MetaClass __init__
A __init__ triggered
Test_MetaClass __call__
Test_MetaClass __call__
我的问题是为什么b = A()
直接进入Test_MetaClass.__call__
而忽略__init__
吗?
my question is why b = A()
straight go to Test_MetaClass.__call__
and ignore __init__
?
推荐答案
这不是您想要的吗? cls._instance
不是None,因此不会执行type.__call__(cls, *args, **kwargs)
:
Isn't that what you wanted? cls._instance
isn't None, so it won't execute type.__call__(cls, *args, **kwargs)
:
>>> type.__call__(A)
A __init__ triggered
<__main__.A object at 0x00BADB30>
通过此调用,调用A.__new__
和A.__init__
来创建/初始化新实例.但是对于您的单身人士,您只需要一个实例.
It's through this call that A.__new__
and A.__init__
get called to create/initialize a new instance. But for your singleton you only want one instance.
这篇关于用元类实现单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文