-
-
Save digitalconceptvisuals/47003d2c9d8ddc283fa6728e599e2906 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# auto inherits a dictionary | |
class auto(dict): | |
# if caller did univ.college | |
def __getattr__(self, name): | |
try: | |
# check if its there | |
return dict.__setitem__(self, name) | |
except: | |
# if not, create it on the fly | |
dict.__setitem__(self, name, auto()) | |
return dict.__getitem__(self, name) | |
# if caller did univ.college = value | |
def __setattr__(self, name, value): | |
# set it in internal dict | |
dict.__setitem__(self, name, value) | |
# if caller did univ['college] | |
def __getitem__(self, value): | |
try: | |
# if found return it | |
return dict.__getitem__(self, value) | |
except: | |
# if not, create it on the fly | |
dict.__setitem__(self, value, auto()) | |
return dict.__getitem__(self, value) | |
univ = auto() | |
univ.college.stream.year = "A+" | |
print(univ) | |
univ2 = auto() | |
univ2['college']['stream']['year'] = "A+" | |
print(univ2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment