jwi*_*720 13 python attributes dictionary overloading
我想知道你是否可以在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'
Run Code Online (Sandbox Code Playgroud)
无论如何都要快速添加我的描述属性,而不必复制dict类并重载构造函数.我觉得这很简单,但我想我错了.
谢谢,J
Sve*_*ach 25
只是来自dict:
class MyDict(dict):
pass
Run Code Online (Sandbox Code Playgroud)
实例MyDict可以具有自定义属性:
>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'
Run Code Online (Sandbox Code Playgroud)