Skip to content

Instantly share code, notes, and snippets.

@dutc
Created August 31, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/892493b7673bd3d47a530a3d3d2aa300 to your computer and use it in GitHub Desktop.
Save dutc/892493b7673bd3d47a530a3d3d2aa300 to your computer and use it in GitHub Desktop.
“Python Expert” Newsletter (Sep 15, 2021): Learning Corner
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'
)
@dutc
Copy link
Author

dutc commented Aug 31, 2021

As you can see:

  • the descriptor protocol is fairly straightforward, and has a number of uses
  • as a consequence of mechanisms such as __slots__ it is not easy to write a complete, pure-Python implementation of __getattr__
  • however, fundamentally, __getattr__ is a simple protocol—a sequence of steps for locating the desired attribute

@dutc
Copy link
Author

dutc commented Aug 31, 2021

For the full write-up and discussion, sign up for the “Python Expert” newsletter!

bit.ly/expert-python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment