creating-a-singleton-in-python和what-is-a-metaclass-in-python
下面这两段代码的执行结果反映了一个问题:很明显元类的存在会影响__call__和__new__的优先级,请问大神能否分析一下两者执行结果不同的原因?
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
print('__new__')
return cls._instance
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
print('__call__')
return cls._instance
class Foo(Singleton):
pass
print('1')
foo1 = Foo()
print('2')
foo2 = Foo()
print(foo1 is foo2) # True
上面这段代码的执行结果
$ python non_metaclass.py
1
__new__
2
__new__
True
class Singleton(type):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
print('__new__')
return cls._instance
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
print('__call__')
return cls._instance
class Foo(metaclass=Singleton):
# 不兼容Python2
pass
print('1')
foo1 = Foo()
print('2')
foo2 = Foo()
print (foo1 is foo2) # True
上面这段代码的执行结果
$ python metaclass.py
__new__
1
__call__
2
__call__
True
如果描述不够详细,请在评论区留一下言,我再改进。
德玛西亚99
眼眸繁星
相关分类