Skip to content

Instantly share code, notes, and snippets.

@chulman444
Created April 27, 2018 03:35
Show Gist options
  • Save chulman444/70e2f245c72d544c622e8546b2b29e19 to your computer and use it in GitHub Desktop.
Save chulman444/70e2f245c72d544c622e8546b2b29e19 to your computer and use it in GitHub Desktop.
Simple code for understanding `__getattr__` and `__getattribute__`
class MyClass():
def __init__(self):
self.foo = "foo"
# Ignored.
def __getattr__(self, attribute):
print("__getattr__ for {} called".format(attribute))
def __getattribute__(self, attribute):
print("__getattribute__ for {} called".format(attribute))
class MyClassA():
def __init__(self):
self.foo = "foo"
def __getattr__(self, attribute):
print("__getattr__ for {} called".format(attribute))
obj = MyClass()
obj.foo # handled by __getattribute__
obj.a # handled by __getattribute__
ooobj = MyClassA()
ooobj.foo # Nothing happens
ooobj.a # handled by __getattr__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment