使用 is 运算符比较 Python class 和 None

Compare Python class to None with is operator

有没有办法使用 is 运算符比较 Python class 和 None?

class DefaultValue:
    def __init__(self, default, value=None):
        self.default = default
        self.value = value

    def __str__(self):
        return str(self.value or self.default)

    def __eq__(self, other):
        return self.value == other

    def __hash__(self):
        return hash(self.value)

d = DefaultValue(False)

str(d) # 'False' 

d == None # True 

d is None # False

有什么我可以在 class 上实现的,以便 is 运算符 return TrueNone?

比较时

https://docs.python.org/3/library/operator.html

按照其他运算符的类似语法覆盖您定义的方法,您可以为 is_ 做一个。希望这对您有所帮助!

您不能重载 is 运算符,因为它用于检查两个变量是否引用相同的值,您永远不需要重载。最相似的是用__eq__方法重载==

class MyClass:
    def __eq__(self, other):
        #code here