我找到了原因。Python變數,list, dict, set是可變物件,str, tuple string int float bool是不可變物件,所以修改class屬性的list、dict、set時,不會生成對應的。實體屬性的實體屬性只有在實體屬性的list、dict、set重新賦值后才會生成。給實體屬性 str 和元組字串 int float bool 賦值會將類屬性中的屬性名復制到實體屬性中,然后重新賦值。
如果我想讓類屬性和實體屬性的串列不同,我可以同時初始化類屬性和實體屬性:
class MyClass:
property = []
def __init__(self):
self.property = []
pass
def add(self, value):
self.property.add(value)
a = MyClass()
print(id(a.property))
print(id(a.__class__.property))
2352192165696
2352189676480
以下是我的原始問題:
我有一個帶有屬性的類和一個帶有空值的串列。當生成了a和b的兩個實體并在屬性中添加元素時,發現該屬性沒有被實體化。使用 id 查看 a.property 和 b.property。記憶體地址是一樣的。為什么?
怎么會property attribute變成一個instance attribute?
我的代碼示例如下:
class MyClass:
property = []
def __init__(self):
pass
def append(self, value):
self.property.append(value)
a = MyClass()
b = MyClass()
a.append(1)
print(a.property)
b.append(1)
print(a.property)
print(b.property)
print(id(a.property))
print(id(b.property))
結果是:
[1]
[1, 1]
[1, 1]
1866383694784
1866383694784
我尊重的結果:
[1]
[1]
[1]
uj5u.com熱心網友回復:
在您的情況下property = []是一個類變數,它與您的類的所有實體共享。我假設,您不想property = []與其他類共享價值。這意味著您需要一個實體變數,它可以像下面這樣定義。
class MyClass:
def __init__(self):
self.property = []
def append(self, value):
self.property.append(value)
這應該給你你預期的輸出,純粹的!
uj5u.com熱心網友回復:
發生這種情況是因為您沒有property在__init__函式內部宣告。
__init__每次創建物件的新實體時都會呼叫它,所以我想這就是您要查找的內容。
嘗試將以下更改應用于您的班級:
class MyClass:
def __init__(self):
self.property = []
def append(self, value):
self.property.append(value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/327274.html
下一篇:以角度向指令添加一個類
