How do predefined descriptors work in functions?

Python functions have descriptors. I believe that in most cases I should not use this directly, but I want to know how this function works? I tried a couple of manipulations with such objects:

  • def a(): return 'x' a.__get__.__doc__ 'descr.__get__(obj[, type]) -> value' 

    What is obj and what type?

  •  >>> a.__get__() TypeError: expected at least 1 arguments, got 0 >>> a.__get__('s') <bound method ?.a of 's'> >>> a.__get__('s')() TypeError: a() takes no arguments (1 given) 

    I am sure that I can not do this trick with functions that take no arguments. Is it only required to call functions with arguments?

  •  >>> def d(arg1, arg2, arg3): return arg1, arg2, arg3 >>> d.__get__('s')('x', 'a') ('s', 'x', 'a') 

    Why is the first argument taken directly by __get__ and everything else returned by the object?

+4
source share
1 answer

a.__get__ is a way to bind a function to an object. In this way:

 class C(object): pass def a(s): return 12 a = a.__get__(C) 

is the gross equivalent

 class C(object): def a(self): return 12 

(Although it is not good to do so: on the one hand, C will not know that it has a related method a , which you can confirm by running dir(C) . In principle, __get__ only performs one part of the binding process).

This is why you cannot do this for a function that takes no arguments - it must accept this first argument (traditionally self ), which passes a particular instance.

+6
source

All Articles