簡體   English   中英

在從dict繼承的類定義中,為什么定義屬性有區別?

[英]In class definition inherited from dict why is there a difference in defining attributes?

在從dict繼承的類中,為什么兩種定義屬性的方式都不產生相同的結果? 為什么我看到attr1但看不到attr2?

class my_dict(dict):
   def __init__(self):
       dict.__init__(self)
       self['attr1'] = 'seen'
       setattr(self, 'attr2', 'unseen')

In [1]: x = my_dict()

In [2]: x
Out[2]: {'attr1': 'seen'}

由於相同的原因:

x = {}
x.foo = 34

不起作用。 dict不能通過定義屬性來工作。

x.attr2
# => 'unseen'

暫無
暫無

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

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