Last active
May 15, 2017 13:26
-
-
Save tomplex/263a7345859d49b6de717e376c2f642e to your computer and use it in GitHub Desktop.
A class for which attributes can be accessed like a `dict`.
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
class DictAttr: | |
def __init__(self): | |
self.attr1 = "Let's go" | |
self.attr2 = "Pens!" | |
def __getitem__(self, item): | |
if getattr(self, item, None): | |
return getattr(self, item) | |
else: | |
raise KeyError("Class has no attribute {}".format(item)) | |
if __name__ == '__main__': | |
d = DictAttr() | |
print(d['attr1'] + ' ' + d['attr2']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment