Operator Overloading

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Thu Nov 25 05:44:18 EST 2004


Peter Maas a écrit :
> Sebastien Boisgerault schrieb:
> 
>> I wonder if the following quotation from the Python Reference Manual 
>> (release 2.3.3) about operator overloading is true :
>>
>> "For example, if a class defines a method named __getitem__(), and x
>> is
>> an instance of this class, then x[i] is equivalent to
>> x.__getitem__(i)"
> 
> [...]
> 
>>>>> from Numeric import *
>>>>> a = array([0.5])
>>>>> a[0]
>>
>>
>> 0.5
>>
>> but
>>
>>
>>>>> a.__getitem__(0)
>>
>>
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>> AttributeError: __getitem__
> 
> 
> The quotation above is true. Short form:
> 
> IF __getitem__ in dict THEN [] works.

That's not true !!! I's true only for classes defined in Python. If you 
try to define a class in C, defining the __getitem__ method does not 
lead to the existence of "[]". But when you define "[]" it creates the 
"__getitem__" method. This is part of the reason why you cannot dervie 
from two types if they derives from different classes written in another 
language and imported in Python (just try to create a class deriving 
from list and dict ...).

Pierre



More information about the Python-list mailing list