簡體   English   中英

在python中將地址更改為“ self”對象不會影響為其創建的對象

[英]Changing the address to “self” object in python will not affect the object created for it

此代碼將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)

擴展我的評論-如果您希望構造函數始終返回完全相同的實例(這被稱為單例),請使用__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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM