我写了自己的向量类:
#! /usr/bin/env python3
class V:
"""Defines a 2D vector"""
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,other):
newx = self.x + other.x
newy = self.y + other.y
return V(newx,newy)
def __sub__(self,other):
newx = self.x - other.x
newy = self.y - other.y
return V(newx,newy)
def __str__(self):
return "V({x},{y})".format(x=self.x,y=self.y)
我想定义 V(0,0) 是一个空向量,这样就可以了:(第一种情况应该返回“向量为空”)
v = V(0,0)
u = V(1,2)
if u:
print (u)
else:
print("Vector is empty")
if v:
print(v)
else:
print("Vector is empty")