要写一个模拟向量的类,要满足以下几点:
- 向量相加时结果还是向量,而且可以被很好的打印出来abs(vector)会返回向量的模向量的数量积
from math import hypot
from matplotlib.pyplot import sca
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self): #重写了repr函数,这样在输出时就不会是对象地址,而是可读的
return F'Vector({self.x}, {self.y})'
def __abs__(self):
return hypot(self.x, self.y)
def __bool__(self): #一般来说,我们自己创建的对象总为真,为了避免bool失去意义,我们便重写了这一函数
return bool(abs(self))
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
__bool__方法
默认的bool可以判断内置类型,但对于我们自己创建的对象,它的返回值总是真的。
如果一个对象没有bool属性,在被调用时,会转向len属性,如果len的返回值为0,则返回False。



