Skip to main content
 首页 » 编程设计

python之如何用一个类支持python中的 `in`操作

2025年05月04日19lyj

我必须修改什么魔术方法才能支持 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 应该是这里的唯一字段)。

请您参考如下方法:

您需要实现 __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__ 上的文档:

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple.