You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3中如何按值语义检查类实例是否存在于列表中

问题原因

Python里用in判断对象是否在列表中时,默认是比较对象的内存地址——你新创建的Demo(4)和列表里的Demo(4)是两个完全独立的实例,地址不一样,所以返回False。

解决方案

方法1:给类加相等判断逻辑(推荐)

给Demo类重写__eq__方法,让它比较实例的属性值,而不是地址。另外最好配套重写__hash__方法,保证相等的实例哈希值一致,符合Python的规范。

from typing import List

class Demo:
    def __init__(self, value: int):
        self.value = value
        
    def __eq__(self, other):
        # 先确认对方是Demo实例,避免和其他类型乱比
        if not isinstance(other, Demo):
            return NotImplemented
        # 直接比较属性值
        return self.value == other.value
    
    def __hash__(self):
        # 用属性值生成哈希
        return hash(self.value)

my_array: List[Demo] = [Demo(4)]
print(Demo(4) in my_array)  # 现在输出True

方法2:手动遍历列表检查

要是没法修改原类的代码,就手动遍历列表,逐个对比属性:

from typing import List

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

# 用any()快速判断是否存在匹配项
exists = any(item.value == target.value for item in my_array)
print(exists)  # 输出True
两种方法怎么选
  • 方法1:一次修改,后续所有涉及Demo实例相等的操作(比如==、集合去重)都会按属性判断,省心又符合直觉。
  • 方法2:不用改类,适合不能修改原类的场景,但每次检查都要写重复逻辑,不够灵活。

内容的提问来源于stack exchange,提问作者cocomac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 14:52:08