一个简单的二维向量类

# _*_ coding: utf-8 _*_
__author__ = 'pythonwu'
__date__ = "2018/5/11 18:21"

from math import hypot

class Vecotr:
def __init__(self,x=0,y=0):
self.x = x
self.y = y

def __repr__(self):
return "Vector(%r,%r)" %(self.x,self.y)

def __abs__(self):
return hypot(self.x,self.y)

def __bool__(self):
return bool(self.x or self.y)

def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vecotr(x,y)

def __mul__(self, scalar):
return Vecotr(self.x*scalar,self.y*scalar)

注释:其实最简单是使用complex类来实现 ,但是当需要多维向量的时候就不是很方便了,这个类可以扩展至n维向量
注释:自定义对象bool方法(内置)__bool__方法不存在的时候,调用__len__判断真假
posted @ 2018-05-11 19:31  五等码农  阅读(1218)  评论(0编辑  收藏  举报