Created
April 27, 2018 03:35
-
-
Save chulman444/70e2f245c72d544c622e8546b2b29e19 to your computer and use it in GitHub Desktop.
Simple code for understanding `__getattr__` and `__getattribute__`
This file contains hidden or 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 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