2012-07-17 55 views
12

我想知道是否可以將屬性添加到Python字典中。從標準庫向python字典添加屬性

class myclass(): 
    def __init__(): 
    self.mydict = {} #initialize a regular dict 
    self.mydict.newattribute = "A description of what this dictionary will hold" 
    >>>AttributeError: 'dict' object has no attribute 'newattribute' 
    setattr(self.mydict,"attribute","A description of what this dictionary will hold" 
    >>>AttributeError: 'dict' object has no attribute 'newattribute' 

無論如何快速添加我的描述屬性,而不必複製字典類和重載構造函數。我認爲這很簡單,但我想我錯了。

感謝, Ĵ

回答

25

剛剛從dict得出:

class MyDict(dict): 
    pass 

MyDict實例可以有自定義屬性:

>>> d = MyDict() 
>>> d.my_attr = "whatever" 
>>> d.my_attr 
'whatever'