Python魔法函数__add__和__mul__能实现对象的加法和乘法运算。
定义类Victor,包含x和y两个属性,实现__add__方法,对两个Victor对象的x和y分别相加组成一个新的Victor对象。
class Victor:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Victor(%r,%r)" % (self.x, self.y)
def __str__(self):
return "Victor,x=%f,y=%f" % (self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Victor(x,y)
创建两个Victor对象,执行加法运算。
v1 = Victor(1,2)
v2 = Victor(3,4)
v3 = v1 + v2
print(v3)
实现__mul__方法,将对象的x和y分别乘以一个常数。
class Victor:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Victor(%r,%r)" % (self.x, self.y)
def __str__(self):
return "Victor,x=%f,y=%f" % (self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Victor(x,y)
def __mul__(self, other):
return Victor(self.x*other, self.y*other)
定义Victor对象,执行乘法运算。
v1 = Victor(1,2)
v2 = v1 * 10
print(v2)
页面更新:2024-02-20
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号