Skip to content

Instantly share code, notes, and snippets.

@tomplex
Last active May 15, 2017 13:26
Show Gist options
  • Save tomplex/263a7345859d49b6de717e376c2f642e to your computer and use it in GitHub Desktop.
Save tomplex/263a7345859d49b6de717e376c2f642e to your computer and use it in GitHub Desktop.
A class for which attributes can be accessed like a `dict`.
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