Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python override dictionary access methods

I have a class devices that inherits from the dict class. devices is a dictionary of dictionaries. I would like to access its keys and values by using a method call syntax, and as well as using the normal syntax. i.e.

class Devices(dict):
    def __init__(self):
        self['device'] = {'name':'device_name'}
    def __getattr__(self, name):
        value = self[name]
        return value
...

mydevices = Devices()
mydevice = mydevices.device #works and mydevices['device'] also works

#But what code do I need for the following?
name = mydevices.device.name 
mydevices.device.name = 'another_name'

I know that if I override the __getattr__ and __setattr__ methods I can achieve this, but as you can see from my code I am not sure how to access a nested dictionary. Does anyone know how to achieve this?

thanks, labjunky

like image 433
labjunky Avatar asked Nov 22 '25 12:11

labjunky


1 Answers

So your answer is pretty much complete anyway. You can define the kind of structure you want with:

class Devices(dict):
    def __init__(self,inpt={}):
        super(Devices,self).__init__(inpt)

    def __getattr__(self, name):
        return self.__getitem__(name)

    def __setattr__(self,name,value):
        self.__setitem__(name,value)

Then a use case would be:

In [6]: x = Devices()

In [7]: x.devices = Devices({"name":"thom"})

In [8]: x.devices.name
Out[8]: 'thom'

Basically just nest your attribute-look-up dictionaries.

like image 102
ebarr Avatar answered Nov 24 '25 01:11

ebarr



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!