python - 是否可以在 python 中使 Instance == string/int/float 或任何数据类型为 True ?

标签 python comparison

class Element:
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __repr__(self):
        return repr(self.value)


example = Element("project", "some project") 

example == "some project"  # False

有没有办法做出上述声明True而不是

example.value == "some project" # True

最佳答案

您可以尝试在类中重载 __eq____ne__ 运算符。

class Element:
    def __init__(self, val):
        self.val = val
    def __eq__(self, other):
        return self.val == other

f = Element("some project")
f == "some project" # True

关于python - 是否可以在 python 中使 Instance == string/int/float 或任何数据类型为 True ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62464668/

相关文章:

list - Haskell - 检查所有列表元素是否唯一

Python Scrapy FormRequest 回调没有发生

python - 从字符串 python 中删除这个身份不明的字符 "\"

python - 如何在python中将时间转换为T Z格式

python - Optional[Type[Foo]] 在 Python 3.5.2 中引发 TypeError

c++ - 虚拟方法作为 Comp 函数进行排序

python - Pyinstaller onefile找不到数据文件

c# - Equals() 方法在比较时无法识别相似/相同的字符

java - 检查两个 true 或两个 false

c++ - 如何比较 C++ 中两个位图屏幕截图的字节与字节