I was wondering if you could add an attribute to a Python dictionary?
JavaScript
x
8
1
class myclass():
2
def __init__():
3
self.mydict = {} # initialize a regular dict
4
self.mydict.newattribute = "A description of what this dictionary will hold"
5
>>> AttributeError: 'dict' object has no attribute 'newattribute'
6
setattr(self.mydict, "attribute", "A description of what this dictionary will hold"
7
>>> AttributeError: 'dict' object has no attribute 'newattribute'
8
Is there anyway to quickly add my description attribute without having to copy the dict class and overloading the constructor. I thought it would be simple, but I guess I was wrong.
Advertisement
Answer
Just derive from dict
:
JavaScript
1
3
1
class MyDict(dict):
2
pass
3
Instances of MyDict
behave like a dict
, but can have custom attributes:
JavaScript
1
5
1
>>> d = MyDict()
2
>>> d.my_attr = "whatever"
3
>>> d.my_attr
4
'whatever'
5