How work pre-defined descriptors in functions?
Asked Answered
P

1

7

Python functions have a descriptors. I believe that in most cases I shouldn't use this directly but I want to know how works this feature? I tried a couple of manipulations with such an objects:

  1.  

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

    What is the obj and what is the type?

  2.  

    >>> 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)
    

    Sure that I can't do this trick with functions which take no arguments. Is it required just only to call functions with arguments?

  3.  

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

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

Plum answered 10/2, 2013 at 16:29 Comment(0)
B
9

a.__get__ is a way to bind a function to an object. Thus:

class C(object):
    pass

def a(s):
    return 12

a = a.__get__(C)

is the rough equivalent of

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

(Though it's not a good idea to do it this way. For one thing, C won't know that it has a bound method called a, which you can confirm by doing dir(C). Basically, the __get__ does just one part of the process of binding).

That's why you can't do this for a function that takes no arguments- it must take that first argument (traditionally self) that passes the specific instance.

Beaut answered 10/2, 2013 at 16:52 Comment(1)
a.__get__(C) is like C.a, not C().a as in your second example.Zumstein

© 2022 - 2024 — McMap. All rights reserved.