Skip to content

Instantly share code, notes, and snippets.

@dishbreak
Last active August 8, 2019 18:49
Show Gist options
  • Save dishbreak/003a880145f30e7769758d55b517f5d3 to your computer and use it in GitHub Desktop.
Save dishbreak/003a880145f30e7769758d55b517f5d3 to your computer and use it in GitHub Desktop.
Proof of concept for __getitem__ / __getattr__
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