Function mistaken for a method

Peter Otten __peter__ at web.de
Thu Jun 1 08:03:27 EDT 2006


Maric Michaud wrote:

> Le Jeudi 01 Juin 2006 13:34, Peter Otten a écrit :
>> A python-coded function has a __get__ attribute, a C-function doesn't.
>> Therefore C1.f performs just the normal attribute lookup while C2.f also
>> triggers the f.__get__(C2(), C2) call via the descriptor protocol which
>> happens to return a bound method.

> I don't think it's about c-coded versus python-coded stuff, C1.f is a
> type, C2.f is a method.

You are right, int is a type not a function, but presence (and
implementation, of course) of __get__ is still the distinguishing factor:

>>> class Int(int):
...     class __metaclass__(type):
...             def __get__(*args): print "XXX", args
...
>>> class C:
...     int = Int
...
>>> C().int
XXX (<class '__main__.Int'>, <__main__.C instance at 0x402948cc>, <class
__main__.C at 0x40281f2c>)

Also:

>>> from math import sin
>>> sin
<built-in function sin>
>>> def son(x): pass
...
>>> class C:
...     sin = sin
...     son = son
...
>>> C().sin(0)
0.0
>>> C().son(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: son() takes exactly 1 argument (2 given)

Peter



More information about the Python-list mailing list