Skip to main content
 首页 » 编程设计

python之是否可以区分类函数 __add__ 中的运算符 += 和 +

2025年05月04日8zhoujg

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

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__()然后 += 将使用它。