Perhaps I am just dumb
Hamish Lawson
hamish_lawson at yahoo.co.uk
Mon Feb 11 09:47:04 EST 2002
wooks wrote:
> Further if I get magic methods right, they are special functions which
> if present enable the object to apply a unique interpretation of a
> python operator.
> So + has standard behaviour but will adopt whatever is specified in
> the __add__ function if one is present for the class.
If an object doesn't have __add__ defined (by itself, its class, or an
inherited class), then it won't have an interpretation *at all* for +.
There's no 'standard behaviour' that is defaulted to. This holds true
for the built-in types too: 4.0 + 3 has an interpretation only because
the float type has __add__ predefined for it.
Thus
4.0 + 3
effectively results in a call to
(4.0).__add__(3)
The second form could actually be directly called that way in Python
2.2 (prior to 2.2, magic methods for built-in types weren't exposed to
the programmer); the brackets around the 4.0 are necessary only to
disambiguate the number from the following dot.
So there is no standard behaviour for + in the sense of some default
action that gets performed in the absense of a defined __add__ method.
However the __add__ method is already defined for most built-in types.
But the operator symbols provide more than just a prettier notation.
When the operand types are different the interpreter will inspect the
operands and will decide which operand to ask to handle the operation.
Thus
4 + 3.0
will effectively result in a call to
(3.0).__radd__(4)
rather than
(4).__add__(3.0)
since integers don't know how to add floats.
Hamish Lawson
More information about the Python-list
mailing list