gpt4 book ai didi

python - 有没有办法将类实例定义为 None ?

转载 作者:行者123 更新时间:2023-12-02 03:42:12 25 4
gpt4 key购买 nike

例如,当我定义了这样一个 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?

最佳答案

虽然您无法覆盖 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

关于python - 有没有办法将类实例定义为 None ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61806609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com