如何定义一个类为空

6

我写了自己的向量类:

#! /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")
3个回答

12
你可以实现特殊方法__bool__
def __bool__ (self):
    return self.x != 0 or self.y != 0

请注意,在Python 2中,特殊方法的名称为__nonzero__

或者,因为您有一个向量,实现__len__并提供实际向量长度可能更有意义。如果未定义__bool__,Python将自动尝试使用__len__方法获取长度并评估是否为零。


当我尝试计算向量长度时,出现以下错误:TypeError: 'float' object cannot be interpreted as an integer。 - Zweedeend
1
这是因为__len__必须返回一个整数。实际向量长度并不总是整数,所以我宁愿实现__bool__ - Markus Unterwaditzer
@MarkusUnterwaditzer 关于整数返回值的观点很好!我没有想到。 - poke
关于__len__方法,这个方法更适合用于获取存储一定数量元素的东西的大小(例如str中的字符或list中的项)吗? - SimonT
1
你可以使用 abs() 函数来获取向量长度,其特殊方法名为 __abs__() - SingleNegationElimination
@SimonT 是的,或者任何由其他事物组成且这些其他事物的数量很重要的东西。 - poke

6

定义 __bool__ 方法,例如:

class V:
    """Defines a 2D vector"""
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __bool__(self):
        return self.x != 0 or self.y != 0

    # Python 2 compatibility
    __nonzero__ = __bool__

1
注意:这在Python 2中不起作用,因为OP的“print”语法表明他们正在使用Python 2。正确的方法是“__nonzero__”。 - Wooble
@Wooble 谢谢,已将 __nonzero__ 添加到答案中。 - phihag

1
如果您只关心输出,只需扩展__str__方法。
def __str__( self ):
    if self.x and self.y :
        return "V({x},{y})".format( x = self.x, y = self.y )
    else:
        return "Vector is empty"



v = V( 0, 0 )
u = V( 1, 2 )
print v
print u

输出结果将为:

Vector is empty

V(1,2)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接