Python - Check instance in __add__ method

Introduction

Without the isinstance test in the following, we could end up with a Adder5 whose val is another Adder5 when two instances are added and __add__ triggers __radd__:

Demo

class Adder5:                                # Propagate class type in results 
   def __init__(self, val): 
       self.val = val #   w w  w.  j  av  a 2  s. co  m
   def __add__(self, other): 
       if isinstance(other, Adder5):        # Type test to avoid object nesting 
           other = other.val 
       return Adder5(self.val + other)      # Else + result is another Adder 
   def __radd__(self, other): 
       return Adder5(other + self.val) 
   def __str__(self): 
       return '<Adder5: %s>' % self.val 

x = Adder5(88) 
y = Adder5(99) 
print(x + 10)                      # Result is another Adder instance 
print(10 + y) 
z = x + y                          # Not nested: doesn't recur to __radd__ 
print(z) 
print(z + 10) 
print(z + z) 
print(z + z + 1) 
z = x + y                          # With isinstance test commented-out 
print(z) 
print(z + 10) 
print(z + z) 
print(z + z + 1)

Result

Related Topic