August 2018
Intermediate to advanced
366 pages
10h 14m
English
With a little effort, we can create a class that leverages dictionaries to contain any attribute we want and allow access both as a dictionary and through properties:
>>> class Bunch(dict): ... def __getattribute__(self, key): ... try: ... return self[key] ... except KeyError: ... raise AttributeError(key) ... ... def __setattr__(self, key, value): ... self[key] = value ... >>> b = Bunch(a=5) >>> b.a 5 >>> b['a'] 5