python - 如何使用类支持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__()
应该返回一个整数。唯一需要的属性是比较相等的对象具有相同的哈希值;建议将对象组件的哈希值混合在一起,通过将它们打包成一个元组并对元组进行哈希处理,这些值也参与了对象的比较。
推荐阅读
- android - Firebase Analytics:具有“Content_type”值的“select_content”事件:(未设置)
- java - 邮件返回 UNKNOWN_URL_SCHEME
- android-wear-2.0 - 待机和环境在 Android 中是相同的
- python - 以 ABC 开头,然后是 B 和/或 C,并以 CBA 结尾的模式的正则表达式
- api - 谷歌一键注册/登录批准请求
- android - ReactNative FlatList 没有以阿拉伯语从右到左正确呈现
- java - finally 之后带有 catch 的嵌套 try 块
- vb.net - LAB、RGB、XYZ 颜色转换不正确,反之亦然
- python - 使用twisted有选择地反向代理到不同的服务器
- angularjs - 如何将文件转换为 .RAR 文件节点 js