Operator commutativity

Westley Martínez anikom15 at gmail.com
Mon Sep 19 18:45:53 CEST 2011


On Mon, Sep 19, 2011 at 01:11:51PM +0200, Henrik Faber wrote:
> Hi there,
> 
> when I have a python class X which overloads an operator, I can use that
> operator to do any operation for example with an integer
> 
> y = X() + 123
> 
> however, say I want the "+" operator to be commutative. Then
> 
> y = 123 + X()
> 
> should have the same result. However, since it does not call __add__ on
> an instance of X, but on the int 123, this fails:
> 
> TypeError: unsupported operand type(s) for +: 'int' and 'X'
> 
> How can I make this commutative?
> 
> Best regards,
> Henri

def __radd__(self, other):
    return self.__add__(self, other)



More information about the Python-list mailing list