rth*_*rth 1 python class addition
我有一个类,其中包含一些数据.对于此类的两个对象,Operator +应合并来自两个对象的数据并返回一个新对象.但是,如果在+ =运算符的情况下,添加对象的数据并返回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
Run Code Online (Sandbox Code Playgroud)
如果__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
Run Code Online (Sandbox Code Playgroud)