14

我想知道您是否可以向 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'

无论如何可以快速添加我的描述属性,而无需复制 dict 类并重载构造函数。我以为这很简单,但我想我错了。

4

1 回答 1

33

只是从dict

class MyDict(dict):
    pass

实例的MyDict行为类似于 a dict,但可以具有自定义属性:

>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'
于 2012-07-17T23:06:18.853 回答