Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of instance and owner in Python descriptors?

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?

like image 859
ng.newbie Avatar asked Oct 18 '25 06:10

ng.newbie


2 Answers

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
like image 97
panda-34 Avatar answered Oct 20 '25 20:10

panda-34


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.

like image 22
bruno desthuilliers Avatar answered Oct 20 '25 20:10

bruno desthuilliers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!