Z
Z
zlodiak2015-12-02 09:33:13
Python
zlodiak, 2015-12-02 09:33:13

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__)

Next, I create 2 objects:
world1 = World('old', boss='demiurg')
world2 = World('new', boss='mr. bin')

After launch, I expect to receive one object with the dimiurg attribute. But I get 2 objects with mr.bin attribute:
[email protected] ~/python/boats2 $ python index2.py
World: {'name': 'new', 'boss': 'mr. bin'}
World: {'name': 'new', 'boss': 'mr. bin'}
worlds quantity: 2

It is not clear why:
1. two objects are obtained instead of one
2. the object has the mr.bin attribute, because in the first place an object with the demiurg attribute is created, and the rest of the objects should be links to it

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Maslennikov, 2015-12-02
@zlodiak

You are changing the name and boss properties of the same object:

>> world1 is world2
True

A
angru, 2015-12-02
@angru

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.

D
Dmitry Demidov, 2015-12-02
@ptitca_zu

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 question

Ask a Question

731 491 924 answers to any question