class Vector:
def __init__(self,x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return 'Vector({0},{1},{2})'.format(self.x,self.y,self.z)
def __neg__(self):
return Vector(-self.x,-self.y,self.z)
def __add__(self, other):
return Vector(self.x + other.x,self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector(self.x - other.x,self.y + other.y, self.z + other.z)
def __mul__(self, other):
return Vector(other * self.x , other * self.y , other * self.z)
def __rmul__(self, other):
return Vector(other * self.x , other * self.y , other * self.z)
if __name__ == '__main__':
v1 = Vector(1,2,3)
v2 = Vector(4,5,6)
print('-v1={}'.format(-v1))
print('v1+v2={}'.format(v1+v2))
print('v1-v2={}'.format(v1-v2))
print('v1*2={}'.format(v1*2))
print('2*v1={}'.format(2*v1))
标签:__,Vector,python,self,v1,other,重载,def
From: https://www.cnblogs.com/jiyiran/p/16868790.html