Closed
Description
Documentation
Doc link: https://docs.python.org/3.10/howto/descriptor.html#invocation-from-an-instance
The code example is bad at https://github.com/python/cpython/blame/eb81c1aea16914347919745e843c982ed831a9fb/Doc/howto/descriptor.rst#L589
getattr(objtype, name)
will go through descriptor.__get__
.
Code Snippet:
class A:
def __get__(self, obj, objtype):
return obj, objtype
class B:
a = A()
print(B().a)
# (<__main__.B object at 0x7ff56d0915e0>, <class '__main__.B'>)
print(B.a) # same as getattr
# (None, <class '__main__.B'>)
Solution
Using __dict__
(or vars) instead of getattr
:
print(vars(B)['a'])
# <__main__.A object at 0x7ff56cfef2b0>