我写了自己的向量类:
#! /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) 是一个空向量,这样就可以了:(第一种情况应该返回“Vector is empty”)
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")
最佳答案
您可以实现特殊方法__bool__
:
def __bool__ (self):
return self.x != 0 or self.y != 0
请注意,在 Python 2 中,特殊方法被命名为 __nonzero__
.
或者,因为您有一个矢量,所以实现 __len__
可能更有意义并提供实际的矢量长度。如果未定义 __bool__
,Python 将自动尝试使用 __len__
方法获取长度并评估它是否不为零。
关于python - 如何定义类何时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18848599/