from math import hypot class Vector: def __init__(self,x,y): self.x = x self.y = y #将一个对象以字符串的形式表示,对比java的tostring方法 __repr__(self): return "Vector(%r,%r)" % (self.x,self.y) 用于计算向量的模 __abs__return hypot(self.x,1)">用于判断向量是否为0向量 __bool__ bool(abs(self)) 向量之间的相加 __add__ other.x y = self.y + other.y Vector(x,y) 向量的标量乘法 __mul__return Vector(self.x * other,self.y * other) v1 = Vector(1,2) v2 = Vector(3,4) print(abs(v1)) print(v1+v2) print(v1*3) v3 = Vector(0,0) print(bool(v3))
输出: