Search code examples
pythonobjectself

Changing the address to "self" object in python will not affect the object created for it


This code changes the address of self object to initial object address in init function from Subsequent initialization of object. But it actually creates new address for the object created. I understand scope of self is only during init function execution. My question is after init method finishes execution does it return anything?


class A:
 addr = None
 def __init__(self):
  if A.addr:
   print("Current object address:",id(self))
   print("First object address:",id(A.addr))
   self = A.addr
   print("Current object address after modification:",id(self))
  else:
   print("Initial address",id(self))
   A.addr = self

>>> a = A()
Initial address 2433753170104
>>> b = A()
Current object address: 2433753170216
First object address: 2433753170104
Current object address after modification: 2433753170104
>>> id(a),id(b)
(2433753170104, 2433753170216)

Solution

  • Expanding on my comment -- if you want a constructor to always return the exact same instance (this is known as a singleton) use the __new__ constructor like so:

    class Singleton:
        _instance = None
        def __new__(cls):
            if cls._instance is None:
                cls._instance = super().__new__(cls)
            return cls._instance
    
    
    s1 = Singleton()
    
    s2 = Singleton()
    
    s1 is s2  # --> True  (this is the same as id(s1) == id(s2))