Operator commutativity

Duncan Booth duncan.booth at invalid.invalid
Mon Sep 19 07:26:08 EDT 2011


Henrik Faber <hfaber at invalid.net> 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?
> 
By defining __radd__

>>> class X:
	def __add__(self, other):
		return "%r + %r" % (self, other)
	def __radd__(self, other):
		return "%r + %r" % (other, self)

	
>>> X() + 123
'<__main__.X object at 0x029C45B0> + 123'
>>> 123 + X()
'123 + <__main__.X object at 0x02101910>'


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list