请先阅读这篇文章:__init__ 是否会在 Singleton 的这种实现中被多次调用?(Python)
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
print 'Singleton.__new__ called with class', cls
if not cls._instance:
print 'Singleton.__new__ creating instance of class', cls
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
cls._instance.__init__(*args, **kwargs)
class Cache(Singleton):
def __init__(self, size=100):
print 'Cache.__init__ called with size', size
for x in range(5):
c = Cache(x)
结果:
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ creating instance of class <class '__main__.Cache'>
Cache.__init__ called with size 0
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>
Singleton.__new__ called with class <class '__main__.Cache'>
它现在似乎可以工作,但问题是在 Singleton 中显式调用继承类init是否是 Pythonic?这有什么可能出错的吗?