在类中重新声明方法“in”

2024-06-16 14:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个抽象数据类型,它创建了一个双链接列表(不确定这是正确的翻译)。在这篇文章中,我创建了一个方法,用正确的方式计算长度,用一个方法来正确地表示它,但是我现在不想创建一个方法,当用户做出类似的事情时:

if foo in liste_adt

会返回正确的答案,但我不知道该用什么,因为in峎不起作用。在

谢谢你


Tags: 方法答案用户in列表iffoo链接
2条回答

你在找^{}?在

object.__contains__(self, item)

Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.

For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference.

简单示例:

>>> class Bar:
...     def __init__(self, iterable):
...         self.list = list(iterable)
...     def __contains__(self, item):
...         return item in self.list
>>>     
>>> b = Bar([1,2,3])
>>> b.list
[1, 2, 3]
>>> 4 in b
False
>>> 2 in b
True

注意:通常当您有这种疑问时,可以在The Python Language ReferenceData Model部分找到参考。在

由于数据结构是一个链表,所以有必要对其进行迭代以检查成员身份。实现__iter__()方法将使if in和{}同时工作。如果有更有效的方法来检查成员资格,请在__contains__()中实现。在

相关问题 更多 >