Last active
August 8, 2019 18:49
-
-
Save dishbreak/003a880145f30e7769758d55b517f5d3 to your computer and use it in GitHub Desktop.
Proof of concept for __getitem__ / __getattr__
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 MyCoolClass(object): | |
def __init__(self, name): | |
self.name = name | |
foo = MyCoolClass("jordan") | |
print(foo.name) | |
try: | |
foo.nothere | |
except AttributeError: | |
print("oops, that didn't work") | |
## Output: | |
## jordan | |
## oops, that didn't work | |
class MyCoolerClass(object): | |
def __init__(self, name): | |
self.name = name | |
def __getitem__(self, item): | |
return "I dunno what %s is" % item | |
def __getattr__(self, attr): | |
return "you want whaat? %s??" % attr | |
foo = MyCoolerClass("vishal") | |
print(foo.name) | |
print(foo.nothere) | |
print(foo[1]) | |
## Output: | |
## vishal | |
## you want whaat? nothere?? | |
## I dunno what 1 is |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment