Say we have a class:
class Foo (object):
... def __init__(self,d):
... self.d=d
... def return_d(self):
... return self.d
… and a dict:
d={'k1':1,'k2':2}
… and an instance:
inst=Foo(d)
Is there a way to dynamically add attributes to return_d so:
inst.return_d.k1 would return 1?
You’d need to do two things: declare
return_das an attribute or property, and return a dict-like object that allows attribute access for dictionary keys. The following would work:Short demo:
The
propertydecorator turns methods into attributes, and the__getattr__hook allows theAttributeDictclass to look up dict keys via attribute access (the.operator).