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.

+3


source to share


2 answers


From the documentation object.__get__(self, instance, owner)

:

owner

is always the owner class, but instance

is the instance that the attribute was accessed, or None

when the attribute is accessed via owner

.



So you don't supply owner

, it gets set depending on how it is called __get__

.

0


source


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>

      

0


source







All Articles