I know that in Python we have to supply __get__
function when implementing a descriptor. The interface is like:
def __get__(self, obj, objtype=None):
pass
My question is:
Why we have to supply objtype
arg? What is objtype
used for?
I did not see some examples about the usage of this arg.
Python's __get__() magic method defines the dynamic return value when accessing a specific instance and class attribute. It is defined in the attribute's class and not in the class holding the attribute (= the owner class).
Python descriptors are a way to create managed attributes. Among their many advantages, managed attributes are used to protect an attribute from changes or to automatically update the values of a dependant attribute. Descriptors increase an understanding of Python, and improve coding skills.
Descriptors are Python objects that implement a method of the descriptor protocol, which gives you the ability to create objects that have special behavior when they're accessed as attributes of other objects.
A descriptor is a mechanism behind properties, methods, static methods, class methods, and super() . Descriptor protocol : In other programming languages, descriptors are referred to as setter and getter, where public functions are used to Get and Set a private variable.
It gives users an option to do something with the class that was used to call the descriptor.
In normal cases when the descriptor is called through the instance we can get the object type by calling type(ins)
.
But when it is called through the class ins
will be None
and we won't be able to access the class object if the third argument was not present.
Take functions in Python for example, each function is an instance of types.FunctionType
and has a __get__
method that can be used 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>
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