Journey to Master Python (WIP)
ageekymonk
14.2K views
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
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 {}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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
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 {}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD Online Participants