4
下面的代碼是如何實施與元類單身,和它運作良好實現單與元類
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__
?
您的元類可能更簡單。不是一個答案,所以你必須處理評論格式。 (class): cls._instance = None;如果cls._instance是無: cls._instance = super(Singleton,cls).__ call __(* args,** kwargs); return cls._instance;' – agf