Answer the question
In order to leave comments, you need to log in
Why is the singleton copied?
Please help me solve the problem. I am trying to use a singleton:
class World(object):
def __new__(cls,*dt,**mp):
if cls.obj is None:
cls.obj = object.__new__(cls,*dt,**mp)
return cls.obj
def __init__(self, name, boss):
self.boss = boss
self.name = name
World.quantity += 1
obj = None
quantity = 0
def __str__(self):
return str(self.__class__.__name__) + ': ' + str(self.__dict__)
world1 = World('old', boss='demiurg')
world2 = World('new', boss='mr. bin')
[email protected] ~/python/boats2 $ python index2.py
World: {'name': 'new', 'boss': 'mr. bin'}
World: {'name': 'new', 'boss': 'mr. bin'}
worlds quantity: 2
Answer the question
In order to leave comments, you need to log in
You are changing the name and boss properties of the same object:
>> world1 is world2
True
and you read in what cases __new__ and __init__ are called and everything will become clear. here for example. you have __init__ called twice on the same object.
Or write "singleton for the lazy" :)
from functools import lru_cache
@lru_cache(maxsize=None)
class S: pass
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question