I am trying to understand descriptors in Python. What I can't seem to get my head around is what is the instance and owner in the descriptor method:
object.__get__(self, instance, owner)
Now I have read the documentation saying that:
owner is always the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner.
Unfortuanately I am having trouble understanding what that means. Does owner refer to the class itself? The class object? Then what is the purpose of instance being passed to it?
The relationships can be illustrated by this code:
class DescriptorClass:
def __get__(self, instance, owner):
return self, instance, owner
class OwnerClass:
descr = DescriptorClass()
ownerinstance = OwnerClass()
self, instance, owner = ownerinstance.descr
assert self is OwnerClass.__dict__['descr']
assert instance is ownerinstance
assert owner is OwnerClass
self, instance, owner = OwnerClass.descr
assert instance is None
Does owner refer to the class itself?
Yes.
The class object?
This is the exact same thing.
Then what is the purpose of instance being passed to it?
How would the descriptor access the instance it's been looked up on else ? If you take the builtin property
type for example, it works by storing accessor functions and calling back on those functions. Those functions expect the current instance as first argument (canonically named "self"). If the descriptor doesn't get the current instance, it obviously cannot pass it to the accessor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With