《中学生可以这样学Python》P166
自定义三维向量类
##自定义三维向量类
class Vector3:
#构造方法,初始化,定义向量坐标
def __init__(self,x,y,z):
self.__x=x
self.__y=y
self.__z=z
#与一个向量相加
def add(self,anotherPoint):
x=self.__x+anotherPoint.__x
y=self.__y+anotherPoint.__y
z=self.__z+anotherPoint.__z
return Vector3(x,y,z)
#减去另一个向量
def sub(self,anotherPoint):
x=self.__x-anotherPoint.__x
y=self.__y-anotherPoint.__y
z=self.__z-anotherPoint.__z
return Vector3(x,y,z)
#向量与一个数字相乘
def mul(self,n):
x,y,z=self.__x*n,self.__y*n,self.__z*n
return Vector3(x,y,z)
#向量除以一个数字
def div(self,n):
x,y,z=self.__x/n,self.__y/n,self.__z/n
return Vector3(x,y,z)
#查看向量各分量的值
def show(self):
print('X:{},Y:{},Z:{}'.format(self.__x,self.__y,self.__z))
#查看向量长度
@property
def length(self):
return(self.__x**2+self.__y**2+self.__z**2)**0.5
#用法演示
v=Vector3(3,4,5)
v.show()
v1=v.mul(3)
v1.show()
v2=v1.add(v)
v2.show()
print(v2.length)
结果:
>>> %Run test9.py
X:3,Y:4,Z:5
X:9,Y:12,Z:15
X:12,Y:16,Z:20
28.284271247461902