Operator Overloading
Sebastien Boisgerault
boisgera at isia.cma.fr
Thu Nov 25 03:14:56 EST 2004
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)"
Consider the following code:
>>> from Numeric import *
>>> a = array([0.5])
>>> a
array([ 0.5])
>>> 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__
I probably understand why the call to __getitem__: there is no
__dict__ attribute in the variable a and not even a __class__
attribute to find what
the class of the variable a is:
>>> a.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: __dict__
>>> a.__class__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: __class__
I didn't know that you could have an instance without a __class__
attribute ... Anyway, if the __class__ attribute was defined, I guess
that the call to a.__getitem__(0) would succeed because "__getitem__"
belongs to the __dict__
of the type of a.
>>> "__getitem__" in type(a).__dict__
True
But then, why does the call to a[0] succeed ? It should be exactly
equivalent
to a.__getitem__[0], right ?
More information about the Python-list
mailing list