python - 如何定义类何时为空

标签 python class

我写了自己的向量类:

#! /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/

相关文章:

python - 使用 scipy 在 Python 中进行曲线拟合

python - Django 和 virtualenv - 添加到 git repo

python - 在Python中解析HTML数据

php - 我是否需要在类中的每个方法中获取 PHP 类对象?

python - 如何在pandas DataFrame中选择名称以X开头的所有列

Python 写入 mkstemp() 文件

c# - 查找存储在数组 C# 中的一组结果的最小值

c++ - 如何合并两个类A和B以定义C++中抽象类的功能

c# - 删除类数组的成员 C#

jquery - 显示表格内容的 <a> 链接的显示/隐藏类函数