我写了自己的向量类:
#! /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")
__len__
必须返回一个整数。实际向量长度并不总是整数,所以我宁愿实现__bool__
。 - Markus Unterwaditzer__len__
方法,这个方法更适合用于获取存储一定数量元素的东西的大小(例如str
中的字符或list
中的项)吗? - SimonTabs()
函数来获取向量长度,其特殊方法名为__abs__()
。 - SingleNegationElimination