首页 > 解决方案 > 如何使用类支持python中的`in`操作

问题描述

我必须修改什么神奇的方法来支持in运营商。这是我正在尝试做的一个例子:

class DailyPriceObj:
    def __init__(self, date, product_id=None):
        self.date = date
        self.product_id = product_id
        self.sd_buy = None

l = list()
l.append(DailyPriceObj(date="2014-01-01"))
DailyPriceObj(date="2014-01-01") in l # how to get this to return True?

换句话说,我希望我的对象“表现得像”该date属性,因此我可以使用它来查看它obj是否在可交互对象中(date此处应该是唯一字段)。

标签: python

解决方案


您需要实施__eq__(并且__hash__为了完整起见):

class DailyPriceObj:
    def __init__(self, date, product_id=None):
        self.date = date
        self.product_id = product_id
        self.sd_buy = None

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.date == other.date

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


l = [DailyPriceObj(date="2014-01-01")]
s = {DailyPriceObj(date="2014-01-01")}

print(DailyPriceObj(date="2014-01-01") in l)
print(DailyPriceObj(date="2014-01-01") in s)

输出

True
True

从文档中__hash__

由内置函数 hash() 调用,用于对散列集合成员的操作,包括 set、frozenset 和 dict。__hash__() 应该返回一个整数。唯一需要的属性是比较相等的对象具有相同的哈希值;建议将对象组件的哈希值混合在一起,通过将它们打包成一个元组并对元组进行哈希处理,这些值也参与了对象的比较。


推荐阅读