[英]Global variable in class shared to other instance
我需要解釋下面的代碼
class Test():
a_variable = []
def add(self, value):
self.a_variable.append(value)
def print(self):
print(self.a_variable)
a = Test()
b = Test()
a.add(1)
b.print()
輸出
[1]
問題:
a_variable
共享給其他實例?注意:我在我的環境中使用 python 3.7.4 並在 Windows 10 上運行
通常,當您嘗試使用實例設置類屬性時,您會創建一個隱藏類屬性的對象屬性。 例如,如果您執行以下操作:
def add(self, value):
self.a_variable = value
你最終會得到:
a.print()
將打印1
b.print()
將打印[]
通過使用.append()
,您可以獲取對類屬性(即Test.a_variable
)的引用並對其進行變異。 這就是為什么它會反映到類的所有實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.