What is the use of the third objtype argument in the Python __get__ descriptor
I know that in Python we have to supply a function __get__
when we implement a descriptor. The interface is like:
def __get__(self, obj, objtype=None):
pass
My question is:
Why should we supply objtype
arg? What is used objtype
for?
I have not seen examples of this argument being used.
source to share
From the documentation object.__get__(self, instance, owner)
:
owner
is always the owner class, butinstance
is the instance that the attribute was accessed, orNone
when the attribute is accessed viaowner
.
So you don't supply owner
, it gets set depending on how it is called __get__
.
It gives users the ability to do something with the class that was used to call the descriptor.
In normal cases, when a handle is called through an instance, we can get the type of the object by calling type(ins)
.
But when it is called through the class it ins
will be None
, and we will not be able to access the class object if the third argument was missing.
Take functions in Python, for example, every function is an instance types.FunctionType
and has a method __get__
that you can use to make that function a bound or unbound method.
>>> from types import FunctionType
>>> class A(object):
pass
...
>>> def func(self):
print self
...
>>> ins = A()
>>> types.FunctionType.__get__(func, ins, A)() # instance passed
<__main__.A object at 0x10f07a150>
>>> types.FunctionType.__get__(func, None, A) # instance not passed
<unbound method A.func>
>>> types.FunctionType.__get__(func, None, A)()
Traceback (most recent call last):
File "<ipython-input-211-d02d994cdf6b>", line 1, in <module>
types.FunctionType.__get__(func, None, A)()
TypeError: unbound method func() must be called with A instance as first argument (got nothing instead)
>>> types.FunctionType.__get__(func, None, A)(A())
<__main__.A object at 0x10df1f6d0>
source to share