2012-07-17 59 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'