Extending: overloading operators (e.g. for a vector class)

Chris Liechti cliechti at gmx.net
Tue May 21 21:57:10 EDT 2002


say i have the follwing class (details ommited):

class Vector2D:
    def __init__(self, x=0, y=0):
        self.x, self.y = x, y
    ...
    def __mul__(self, other):
        if type(other) in (int, float):
            return Vector2D( self.x*other, self.y*other )
        else:
            raise NotImplementedError

now i want to program this as a C extension type (for practise, i know that 
there are existing extensions to represent a vector).

it seems to me tp_as_number supports __mul__ for numbers, but only for 
instances of the same type, a coercion function (nb_coerce) can help in 
some cases (e.g. converting a complex), but i can't use it to represent a 
scalar (int, long, float) in this case.

and there seems so be an other place where a __mul__ can be emulated: 
sq_repeat for sequences. can/must i define both, or none?

should i provide these methods (__mul__, __add__ etc.) throug getattr and 
implement them just as i would do it when not overloading an operator (like 
defining a .multiply(other) method but name it __mul__)?

i expect similar problems when using __add__ with a tuple/list etc.
(i first thought that the % operator of strings could be a source of 
information, but i found out that this is handled as special case :-(


thanks for any hints, pointers, examples...

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list