如何使用类支持 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这里应该是一个唯一的字段(。

你需要实现__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__()应返回一个整数。唯一必需的属性是对象 比较相等具有相同的哈希值;建议混合 以及对象组件的哈希值,这些组件也 通过将对象打包到元组中来比较对象,并在比较中发挥作用,并且 对元组进行哈希处理。

您可以实现__eq__

,使两种检查方法都有效:

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 self.date == other
l = list()
l.append(DailyPriceObj(date="2014-01-01"))
# both ways work:
print(DailyPriceObj(date="2014-01-01") in l)  # True
print("2014-01-01" in l)  # True

最新更新