python - 如何检查 Python 3 的列表中是否存在类的实例?

标签 python list class

在 Python 3 中,我有一个列表 (my_array),其中包含 Demo 类的实例,并在该实例上设置了特定属性。就我而言,该属性是 value: int = 4

给定 Demo 类的实例,如何确定该实例是否已存在于具有相同属性的 my_array 中。这是我的问题的 MCRE:

from typing import List
class Demo:
    def __init__(self, value: int):
        self.value = value
        
my_array: List[Demo] = [Demo(4)]

print(Demo(4) in my_array)  # prints False

但是,Demo(4) 显然已经存在于列表中,尽管它打印 False

我浏览了类似的问题,但它们不相关。

如何检查列表中是否已存在?

最佳答案

您需要添加 equality function演示:

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

P.S,从 Python 3.9 开始,您不需要导入 List 并只需使用:

my_array: list[Demo] = [Demo(4)]

关于python - 如何检查 Python 3 的列表中是否存在类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77443428/

相关文章:

python - 如何使用python删除json文件中的特定字段

python - 在python中的嵌套元组中查找单个项目的计数

c# - 将 List<List<object>> 转换为 IList<IList<object>>

python - Python中的条件计数

c++ - 将类声明为类的一部分的问题

html - CSS - 无序列表 - 类,id 不工作

python - 根据多个日期条件过滤 Dataframe

python - 我尝试在 tensorflow 数据管道上使用 albumentations 时出错

python - 如何限制 for 循环根据它们在 python 中的值从列表中打印前几个元素?

swift - 我应该把我的函数放在哪里?