有没有一种方法可以定义一个类实例为None?

时间:2020-05-14 20:13:54

标签: python python-3.x

例如,当我定义了一个Node类时。

class Node:
    def __init__(self, val=None, next=None):
        self.val = val
        self.next = next

    def __bool__(self):
        return self.val is not None

当我使用空参数初始化它时,如下所示。有没有一种自定义方法来说a is None

a = Node()
a is None # False, but can it be true if I want?

3 个答案:

答案 0 :(得分:4)

虽然您不能覆盖is比较,但是如果要快速检查类中的特定参数(或条件)是否应在比较时产生True,则可以至少覆盖相等运算符,例如:

class Node:
    def __init__(self, val=None, next=None):
        self.val = val
        self.next = next

    def __eq__(self, obj):
        return obj == self.val

n = Node()
print(n == None)  # True
n = Node(5)
print(n == None)  # False

答案 1 :(得分:2)

否,但是...

您不能覆盖isandor运算符。

定义__bool__可使您编写类似的语句

class Node:
    def __init__(self, val):
        self.val = val

    def __bool__(self):
        return self.val is not None   # <--- added "return"

for val in (0, 1, True, None):
    n = Node(val)
    # These three are equivalent
    if n:
        assert n.__bool__()
        assert n.val is not None
    # These three are equivalent
    else:
        assert not n.__bool__()
        assert n.val is None

https://docs.python.org/3/reference/datamodel.html#object.bool

答案 2 :(得分:2)

这可能无法完全满足您的要求,但是您可以覆盖__new__类方法,以便在不带任何参数的情况下调用类构造函数时,将返回None对象,而不是Node

我认为这应该起作用(我的元类知识不完整)。

class Node:
    def __new__(cls, val=None, next=None):
        if val is None and next is None:
            return None

        return super().__init__(cls, val, next)

    def __init__(self, val, next):
        if self is None:
            return

        ...

但是,我有责任建议您不要走这条路。摆弄__new__既棘手又危险,可能比它值得的麻烦还要多。