python使用add进行重载加法

Python (155) 2023-06-30 22:07:51

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、先定义一个类:

classPoint:
def__init__(self,x,y):
self.x=x
self.y=y

>>>a=Point(2,4)
>>>b=Point(3,5)
>>>a+b
Traceback(mostrecentcalllast):
File"/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",line2862,inrun_code
exec(code_obj,self.user_global_ns,self.user_ns)
File"<ipython-input-7-f96fb8f649b6>",line1,in<module>
a+b
TypeError:unsupportedoperandtype(s)for+:'Point'and'Point'

很显然 a 和 b 并不能相加,但是我们可以定义一个方法让它们实现相加。

classPoint:
def__init__(self,x,y):
self.x=x
self.y=y

#定义一个add方法
defadd(self,other):
returnPoint(self.x+other.x,self.y+other.y)

>>>a=Point(2,4)
>>>b=Point(3,5)
>>>c=a.add(b)
>>>c.x
Out[6]:5

2、通过一个 add 方法,我们实现了它们的相加功能。但是,我们还是习惯使用加号,事实上,我们只要改下函数名就可以使用 + 进行运算了。

def__add__(self,other):
returnPoint(self.x+other.x,self.y+other.y)

很显然 + 就是调用类的 __add__ 方法,因为我们只要加入这个方法就能够实现加法操作。

以上就是python使用add进行重载加法,希望能对大家有所帮助。更多Python学习指路:python基础教程

THE END

发表回复