简体   繁体   English

有没有办法将 class 实例定义为 None?

[英]Is there a way to define a class instance is None?

For example, when I have such a Node class defined.例如,当我定义了这样一个Node class 时。

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

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

When I initialize it with empty arguments, like below.当我用空的 arguments 初始化它时,如下所示。 Is there a way to self-define method to say a is None ?有没有办法自定义方法说a is None

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

While you cannot override the is comparison, you can at least override the equality operator if you want to quickly check up whether a specific parameter (or condition) within your class should yield True on comparison, eg:虽然您不能覆盖is比较,但如果您想快速检查 class 中的特定参数(或条件)是否应该在比较时产生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

No, but...不是,但...

You cannot override the is , and , or or operators.您不能覆盖isand 、 or or运算符。

Defining __bool__ allows you to write statements like定义__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. https://docs.python.org/3/reference/datamodel.html#object。 bool 布尔

This may not do exactly what you want but you could overwrite the __new__ class method so that, when the class constructor is called with no arguments, the None object is returned instead of an instance of Node . This may not do exactly what you want but you could overwrite the __new__ class method so that, when the class constructor is called with no arguments, the None object is returned instead of an instance of Node .

I think this should work (my metaclass knowledge is spotty).我认为这应该可行(我的元类知识参差不齐)。

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

        ...

It is my duty to recommend that you not go down this route, however.但是,我有责任建议您不要沿着这条路线走 go。 Fiddling with __new__ is tricky and dangerous and is probably more trouble than it's worth.摆弄__new__既棘手又危险,而且可能比它的价值更麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM