Jan-09-2019, 06:53 PM
That seems like a lot of work. Why not just use
dict
as a the parent class, and add in __getattr__
and __setattr__
methods?>>> class attrdict(dict): ... def __getattr__(self, key): ... return self[key] ... def __setattr__(self, key, value): ... self[key] = value ... >>> spam = attrdict({"foo": "bar", 42: "carrots"}) >>> spam {'foo': 'bar', 42: 'carrots'} >>> spam.foo 'bar' >>> spam[42] 'carrots' >>> print(spam) {'foo': 'bar', 42: 'carrots'} >>> spam.cat = "dog" >>> spam {'foo': 'bar', 42: 'carrots', 'cat': 'dog'} >>> spam.items() dict_items([('foo', 'bar'), (42, 'carrots'), ('cat', 'dog')]) >>> for key in spam: ... print(key) ... foo 42 cat