Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 901
root Avatar asked Nov 22 '25 03:11

root


1 Answers

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).

like image 128
Martijn Pieters Avatar answered Nov 24 '25 18:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!