Python - Reusing __add__ in __radd__

Introduction

The following code implement all three of these schemes, and return the same results as the original.

Demo

class Adder2: 
   def __init__(self, val): 
       self.val = val # from w w w.  ja v  a2 s . c o  m
   def __add__(self, other): 
       print('add', self.val, other) 
       return self.val + other 
   def __radd__(self, other): 
       return self.__add__(other)              # Call __add__ explicitly 

class Adder3: 
   def __init__(self, val): 
       self.val = val 
   def __add__(self, other): 
       print('add', self.val, other) 
       return self.val + other 
   def __radd__(self, other): 
       return self + other                     # Swap order and re-add 

class Adder4: 
   def __init__(self, val): 
       self.val = val 
   def __add__(self, other): 
       print('add', self.val, other) 
       return self.val + other 
   __radd__ = __add__                          # Alias: cut out the middleman

Related Topic