Journey to Master Python (WIP)
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Dynamic Attributes
Handling Unknown Instance attributes
You can dynamically respond to get instance attributes. python provides special method called __getattr__
which can be implemented to respond to get attributes
In the below example we are subclassing dict so that we can get elements as class attributes rather than with element accessor.
Dynamic get attributes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class BetterDict(dict):
def __init__(self, *args):
super().__init__(*args)
def __getattr__(self, key):
if self.__contains__(key):
return self.__getitem__(key)
else:
#For unknown key return empty dict
return {}
addressbook = BetterDict()
addressbook['jason'] = {'name': 'Jason Bourne', 'age': 40}
print(addressbook.jason)
print(addressbook.ironman)
Press desired key combination and then press ENTER.
Setting unknown instance attributes
Extending the above example we can also set attributes using __setattr__
. __setattr__
gets called when there is no such attribute to set. We can implement it for our purpose.
Dynamic set attributes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BetterDict(dict):
def __init__(self, *args):
super().__init__(*args)
def __getattr__(self, key):
if self.__contains__(key):
return self.__getitem__(key)
else:
#For unknown key return empty dict
return {}
def __setattr__(self, key, value):
self.__setitem__(key, value)
addressbook = BetterDict()
print(addressbook.ironman)
addressbook.ironman = {'name' : 'Iron Man', 'age': 35}
print(addressbook.ironman)
Press desired key combination and then press ENTER.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content