1

I have a class, which contains some data. Operator + for two objects of such class should merge data from both objects and returns a new object. However, it should be much better if in the case of += operator would append data from the added object and return self. Here some pseudo code to demonstrate what I want to achieve.

class BiGData:
  def __init__(self):
    self.data=[]
  def __add__(self,x):
    if (this is just a +):
      newData=BigData()
      newData.data += self.data
      newData.data += x.data
      return newData
    else: #(this is the += case)
      self.data += x.data
      return self

If these two case of usage __add__ function can be distinguished, Python code would much better read and understand! Consider this:

x,y=BigData(),BigData()
z = x + y # z is a new object of the BigData class, 
          # which collects all data from both x and y
          # but data in x and y are intacked
x += y    # just append data from y to x
          # data in x has been changed
rth
  • 2,946
  • 1
  • 22
  • 27
  • 1
    As a general rule, `+=` is a different operator, so can be overriden separately. If it is not defined separately, the default implementation will just use `+` and reassign the result. – Mad Physicist May 03 '18 at 20:31
  • @MadPhysicist yes I do understand now. Somehow __iadd__ sneaked behind my attention – rth May 03 '18 at 21:59

2 Answers2

7

No, it is not possible.

But if you implement __iadd__() then += will use that instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

object.__iadd__(self, other) for +=

object.__radd__(self, other) for +

see datamodel for reference

Yaroslav Surzhikov
  • 1,568
  • 1
  • 11
  • 16
  • 2
    `__iadd__` and just plain `__add__`. You only really want `__radd__` for weird cases and where addition is not commutative for some reason. – Mad Physicist May 03 '18 at 20:30