root
root

Reputation: 80336

Python Classes: adding dynamic attributes to methods

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?

Upvotes: 2

Views: 767

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121168

You'd need to do two things: declare return_d as an attribute or property, and return a dict-like object that allows attribute access for dictionary keys. The following would work:

class AttributeDict(dict): 
    __getattr__ = dict.__getitem__

class Foo (object):
    def __init__(self,d):
        self.d=d

    @property
    def return_d(self):
        return AttributeDict(self.d)

Short demo:

>>> foo = Foo({'k1':1,'k2':2})
>>> foo.return_d.k1
1

The property decorator turns methods into attributes, and the __getattr__ hook allows the AttributeDict class to look up dict keys via attribute access (the . operator).

Upvotes: 9

Related Questions