Redeclaration of the method “in” within a class

こ雲淡風輕ζ 提交于 2019-12-12 12:06:23

问题


I am creating an Abstract Data Type, which create a doubly linked list (not sure it's the correct translation). In it I have create a method __len__ to calcucate the length of it in the correct way, a method __repr__ to represent it correctly, but I wan't now to create a method which, when the user will make something like:

if foo in liste_adt

will return the correct answer, but I don't know what to use, because __in__ is not working.

Thank you,


回答1:


Are you looking for __contains__?

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.

Quick example:

>>> 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

Note: Usually when you have this kind of doubts references can be found in the Data Model section of the The Python Language Reference.




回答2:


Since the data structure is a linked list, it is necessary to iterate over it to check membership. Implementing an __iter__() method would make both if in and for in work. If there is a more efficient way for checking membership, implement that in __contains__().



来源:https://stackoverflow.com/questions/9428419/redeclaration-of-the-method-in-within-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!