class 函数 __add__ 中的运算符 += 和 + 是否可以区分?

Is it possible to distinguish operators += and + in class function __add__?

我有一个 class,其中包含一些数据。运算符 + 对于此类 class 的两个对象应该合并来自两个对象的数据并且 returns 是一个新对象。但是,如果在 += 运算符的情况下会从添加的对象和 return 自身附加数据,那应该会好得多。这里有一些伪代码来演示我想要实现的目标。

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

如果能区分这两种使用__add__函数的情况,Python代码会更好看和理解!考虑一下:

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

不,不可能。

但如果您实施 __iadd__(),那么 += 将使用它。

object.__iadd__(self, other) 对于 +=

object.__radd__(self, other) 对于 +

参考datamodel