Created
August 31, 2021 14:47
-
-
Save dutc/892493b7673bd3d47a530a3d3d2aa300 to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 15, 2021): Learning Corner
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 A: | |
x = 1 | |
class B(A): | |
y = 20 | |
class D: | |
def __get__(self, instance, owner): | |
return 50_000 | |
class C(B): | |
z = 300 | |
def __init__(self): | |
self.w = 4_000 | |
abc = D() | |
def getattr_(obj, attr): | |
# __getattribute__ | |
if attr in obj.__dict__: | |
return obj.__dict__[attr] | |
for cls in type(obj).__mro__: | |
if attr in cls.__dict__: | |
rv = cls.__dict__[attr] | |
if hasattr(rv, '__get__'): | |
return rv.__get__(obj, cls) | |
return rv | |
# __getattr__ | |
if __name__ == '__main__': | |
obj = C() | |
print( | |
f'{getattr (obj, "x") = :,}', | |
f'{getattr_(obj, "x") = :,}', | |
f'{getattr (obj, "y") = :,}', | |
f'{getattr_(obj, "y") = :,}', | |
f'{getattr (obj, "z") = :,}', | |
f'{getattr_(obj, "z") = :,}', | |
f'{getattr (obj, "w") = :,}', | |
f'{getattr_(obj, "w") = :,}', | |
f'{getattr (obj, "abc") = :,}', | |
f'{getattr_(obj, "abc") = :,}', | |
sep='\n' | |
) |
For the full write-up and discussion, sign up for the “Python Expert” newsletter!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As you can see:
__slots__
it is not easy to write a complete, pure-Python implementation of__getattr__
__getattr__
is a simple protocol—a sequence of steps for locating the desired attribute