Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
attrdict.py
#4
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
Reply


Messages In This Thread
attrdict.py - by Skaperen - Jan-02-2019, 08:30 PM
RE: attrdict.py - by scidam - Jan-05-2019, 01:45 AM
RE: attrdict.py - by Skaperen - Jan-09-2019, 06:40 PM
RE: attrdict.py - by nilamo - Jan-09-2019, 06:53 PM
RE: attrdict.py - by Skaperen - Jan-10-2019, 12:51 AM
RE: attrdict.py - by Skaperen - Jan-10-2019, 06:35 AM
RE: attrdict.py - by Gribouillis - Jan-10-2019, 08:49 AM
RE: attrdict.py - by Skaperen - Jan-11-2019, 03:47 PM
RE: attrdict.py - by nilamo - Jan-11-2019, 04:26 PM
RE: attrdict.py - by Skaperen - Jan-12-2019, 12:57 AM
RE: attrdict.py - by nilamo - Jan-13-2019, 02:10 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020