In article <j5797e$s57$1...@speranza.aioe.org>,
 Henrik Faber <hfa...@invalid.net> wrote:

> On 19.09.2011 13:23, Paul Rudin wrote:
> > Henrik Faber <hfa...@invalid.net> writes:
> > 
> >> How can I make this commutative?
> > 
> > Incidentally - this isn't really about commutativity at all - the
> > question is how can you define both left and right versions of add,
> > irrespective of whether they yield the same result.
> 
> Right. The operator+ in my case just happens to be commutative and I
> wanted a language way to express this.
> 
> > I think __radd__ is what you're after.
> 
> It is, thank you very much - I knew there was some way to get this done
> nicely. Perfect! :-)

__radd__() only solves the problem if the left-hand operand has no 
__add__() method itself.

class C1:
    def __add__(self, other):
        print "C1.__add__()"
    def __radd__(self, other):
        print "C1.__radd__()"

class C2:
    def __add__(self, other):
        print "C2.__add__()"
    def __radd__(self, other):
        print "C2.__radd__()"

c1 = C1()
c2 = C2()

c1 + c2
c2 + c1

$ python radd.py
C1.__add__()
C2.__add__()
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to