Back
Close

Journey to Master Python (WIP)

ageekymonk
8,209 views
Previous: Collections Module Next: Callables

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
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)
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
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)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
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