static, class and instance methods (Reposting On Python-List Prohibited)
Peter Otten
__peter__ at web.de
Thu Oct 6 05:35:31 EDT 2016
ast wrote:
>
> "Lawrence D’Oliveiro" <lawrencedo99 at gmail.com> a écrit dans le message de
> news:f5314bdd-a98f-4a16-b546-bd8efe4dd568 at googlegroups.com...
>> On Thursday, October 6, 2016 at 7:54:08 PM UTC+13, ast wrote:
>>> But there is no decorator, why ? Is python doing the conversion
>>> of funct2 to a descriptor itself, behind the scene ?
>>
>> Every function is already a descriptor. So you get the instance-method
>> behaviour automatically.
>>
>>> * static methods are decorated too
>>
>> This is to turn off the instance-method behaviour.
>
>
> I do not understand your answer.
> Consider this function:
>
> def add(a, b):
> return a+b
>
> You say that a function is always stored as
> a descriptor object, so when I execute
>
> sum = f(4, 6)
>
> from which class it is supposed to come from ?
It doesn't matter. You can invoke it in the usual way
>>> def add(a, b): return a + b
...
>>> add(2, 3)
5
and even put it into an instance:
>>> class A: pass
...
>>> a = A()
>>> a.foo = add
>>> a.foo(3, 4)
7
Only when you put it into a class the first argument will be the instance
>>> A.bar = add
>>> a.bar(5, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 2 positional arguments but 3 were given
because under the hood add.__get__() is invoked. Doing it manually:
>>> add.__get__(a)(5, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 2 positional arguments but 3 were given
Unlike Python functions those implemented in C don't support the descriptor
protocol out of the box, so
>>> A.baz = sum
>>> a.baz([1,2,3])
6
does not pass the instance a as an argument.
More information about the Python-list
mailing list