來源:如果新收益類實例Python and the Singleton Pattern是否__init__被Singleton的這個實現調用了多次? (蟒蛇)
根據頂端回答初始化最upvoted評論被多次調用。
所以我檢查了這一點:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
print 'Singleton.__new__ called with class', cls
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Cache(Singleton):
def __init__(self, size=100):
print 'I am called with size', size
class S(Singleton):
def __init__(self, param):
print 'I am S with param', param
c = Cache(20)
s = S(10)
結果:
Singleton.__new__ called with class <class '__main__.Cache'>
I am called with size 20
Singleton.__new__ called with class <class '__main__.S'>
I am S with param 10
顯然初始化沒有所謂的類從單身繼承不止一次。同時處理這個問題的Python已經改變了(考慮到這個問題是在2008年提出的),還是我在這裏丟失了smth?
現在我明白了,我認爲他們正在談論一些繼承魔法,並沒有想到一件簡單的事情。無論如何,請看看http://stackoverflow.com/questions/18386562/python-singleton-take -2 – LetMeSOThat4U