class_inplace_op.py 859 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Case 1: Immutable object (e.g. number-like)
  2. # __iadd__ should not be defined, will be emulated using __add__
  3. class A:
  4. def __init__(self, v):
  5. self.v = v
  6. def __add__(self, o):
  7. return A(self.v + o.v)
  8. def __repr__(self):
  9. return "A(%s)" % self.v
  10. a = A(5)
  11. b = a
  12. a += A(3)
  13. print(a)
  14. # Should be original a's value, i.e. A(5)
  15. print(b)
  16. # Case 2: Mutable object (e.g. list-like)
  17. # __iadd__ should be defined
  18. class L:
  19. def __init__(self, v):
  20. self.v = v
  21. def __add__(self, o):
  22. # Should not be caled in this test
  23. print("L.__add__")
  24. return L(self.v + o.v)
  25. def __iadd__(self, o):
  26. self.v += o.v
  27. return self
  28. def __repr__(self):
  29. return "L(%s)" % self.v
  30. c = L([1, 2])
  31. d = c
  32. c += L([3, 4])
  33. print(c)
  34. # Should be updated c's value, i.e. L([1, 2, 3, 4])
  35. print(d)