如何為類屬性和實體屬性定義不同的地址?
這個問題困擾了我很久,除非我洗掉了class屬性的定義,但是想使用class屬性。
我在類屬性和實體屬性中定義了一個同名的字典。如何使記憶體地址不同?我嘗試了多種方法來洗掉類屬性的內容。有沒有其他方法?
我的演示代碼如下:
class MyClass:
bar: dict = {}
def __init__(self):
bar: dict = {}
print(id(MyClass.bar))
a = MyClass()
print(id(a.bar))
1914627629760
1914627629760
uj5u.com熱心網友回復:
class MyClass:
bar: dict = {}
def __init__(self):
self.bar = {}
print(id(MyClass.bar))
a = MyClass()
print(id(a.bar))
2318292079808
2318295104384
也就是說,我不知道我們為什么要這樣做,而且幾乎 100% 的可能性會讓(下一個)維護這個代碼庫的人在未來 2 年內發瘋。
解釋:
您沒有在__init__()函式中“保存”變數。
嘗試運行:
class MyClass:
def __init__(self):
self.a = 1 # setting attribute a to value 1
b = 2 # b is not an attribute, it's just a local variable
m = MyClass()
print(m.a) # this will work
print(m.b) # this will not
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336781.html
