在python中将地址更改为“ self”对象不会影响为其创建的对象

时间:2019-01-18 11:38:00

标签: python object self

此代码将init函数中自身对象的地址从对象的后续初始化更改为初始对象地址。但是它实际上为创建的对象创建了新地址。我了解self的范围仅在init函数执行期间。我的问题是init方法完成执行后是否返回任何内容?


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)

1 个答案:

答案 0 :(得分:1)

扩展我的评论-如果您希望构造函数始终返回完全相同的实例(称为单例),请使用__new__构造函数,如下所示:

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