评论中的人要求我提供实际的代码,所以我删除了旧的示例。
我正在制作this ,并且我希望两个具有相同标题的 Page
比较相等。我已经对 Page 类执行了此操作:
def __eq__(self, other):
return self.title == other.title
但如果我这样做,那就不是真的:
>>> import mw_api_client as mwc
>>> w = mwc.Wiki('https://en.wikipedia.org/w/api.php')
>>> a = [w.page(str(i)) for i in range(20)]
>>> w.page('0') in a
False
我怎样才能做到这一点?
最佳答案
列表的 __contains __
方法记录在“成员资格测试”部分中:
https://docs.python.org/3.6/reference/expressions.html#membership-test-details
For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression
x in y
is equivalent toany(x is e or x == e for e in y)
.
对于您的特定用例,您需要覆盖 __contains__
- 但是您不能只覆盖列表上的 __contains__
- 例如:
a = []
a.__contains__ = lambda: True
AttributeError: 'list' object attribute '__contains__' is read-only
因此,解决方案是创建一个包装列表的自定义类,并提供它自己的 __contains__
方法。类似以下内容(请注意,我使用的是字典,因此在此示例中使用 obj['title']
而不是 obj.title
- 您可能还想测试更多内容在 __contains__
中,例如类型比较等)。我在这里使用 UserList
,因为它提供了一个很好的 list
类来继承,并使列表内容在 data
中可用:
from collections import UserList
class MyList(UserList):
def __init__(self, lst):
self.data = lst
def __contains__(self, obj):
"""Return True if any item in the list has a title, and the title matches that of the passed-in dict"""
return any(obj['title'] == x['title'] for x in self.data if 'title' in x)
mr = {"title": "mr"}
mrs = {"title": "mrs"}
dr = {"title": "dr"}
random = {"foo": "bar"}
x = [mr, mrs, random]
y = MyList(x)
print(mr in y) # True
print(dr in y) # False
y.append(dr)
print(dr in y) # True
关于Python *list* "in"运算符 : equality, 哈希检查,还是身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48850824/