[英]python class attributes vs instance attributes
我有以下代碼片段:
class House:
area = "Munich"
def __init__(self, street, number):
self.street = street
self.num = number
h1 = House("Offenbachstarsse", 123)
h2 = House("Offenbachstarsse", 145)
print(h1.street + ',' + str(h1.num) + ',' + h1.area)
print(h2.street + ',' + str(h2.num)+ ',' + h2.area)
output ** Offenbachstarsse,123,Munich Offenbachstarsse,145,慕尼黑 **
h2.area = "Regensburg"
print(h1.street + ',' + str(h1.num) + ',' + h1.area)
print(h2.street + ',' + str(h2.num)+ ',' + h2.area)
output ** Offenbachstarsse,123,Munich Offenbachstarsse,145,Regensburg **
House.area = "Germany"
print(h1.street + ',' + str(h1.num) + ',' + h1.area)
print(h2.street + ',' + str(h2.num)+ ',' + h2.area)
output ** Offenbachstarsse,123,Germany Offenbachstarsse,145,Regensburg **
有人可以解釋一下,如何更新 class 屬性嗎? 當使用 class 更新 class 屬性時,為什么它只更改 h1 object 區域而不更改 h2 object 區域?
據我所知,當使用 object 更改時,class 屬性“區域”僅更改所用 object 的 class 屬性的值,即 h2.area ="Regensburg" 僅更新 h2.area,而我的預期是在使用 class 的 class 屬性也應該反映在所有 object 實例中。 示例:House.area = "Germany" 將導致 h2.area = "Germany" 和 h1.area = "Germany"。 但是我看到 h2.area 仍然顯示本地更新。 這是為什么?
當您h2.area="Regensburg"
時,您創建了該名稱的實例屬性。 就像您執行h2.whatever=123
並創建一個新屬性一樣。 class 屬性仍然存在,只是不能直接訪問。 做del h2.area
然后print(h2.area)
你自己看看!
快速演示:
>>> class Test:
... a = 1
...
>>> t1 = Test()
>>> t2 = Test()
>>> t1.a = "this creates an instance attribute"
>>> t1.b = "just like this normally creates an instance attribute"
>>> t1.a
'this creates an instance attribute'
現在,讓我們檢查每個對象的 dict dunder:
>>> t2.__dict__
{}
>>> t1.__dict__
{'a': 'this creates an instance attribute', 'b': 'just like this normally creates an instance attribute'}
>>> Test.__dict__
mappingproxy({'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None})
如您所見,t1 存儲了自己的屬性。 t2 沒有 - 當我們執行 t2.a 時,我們沒有找到它,所以我們檢查 class 屬性。
現在,大揭秘:
>>> del t1.a
>>> t1.a
1
>>> t1.__dict__
{'b': 'just like this normally creates an instance attribute'}
我們刪除了 instance 屬性,所以我們在執行 t1.a 時可以再次看到 class 屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.