Прочитайте это первое PLS: does __init__ get called multiple times with this implementation of Singleton? (Python)Python синглтон, возьмите 2
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 является питоническим? Есть ли что-то, что может пойти не так с этим?
это становится личным: http://stackoverflow.com/questions/18386776/python-singleton-take-3 – LetMeSOThat4U