Retraining the in method inside a class

I am creating an abstract data type that creates a doubly linked list (not sure if this is the correct translation). In it, I created the __len__ method to correctly calculate its length, the __repr__ method to represent it correctly, but now I will not create a method that, when the user does something like:

if foo in liste_adt 

will return the correct answer, but I do not know what to use, because __in__ does not work.

Thanks,

+4
source share
2 answers

Are you looking for __contains__ ?

object.__contains__(self, item)

Called to run membership test statements. Should return true if the element is in itself, false otherwise. For matching objects, this should take into account the matching keys, not the values ​​or pairs of key elements.

For objects that do not define __contains__() , the membership test first tries to iterate through __iter__() , then the old sequence iteration protocol through __getitem__() , see this topic in the help system .

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 such doubts, links can be found in the Data Model in the Python Language Reference section.

+11
source

Since the data structure is a linked list, you must iterate over it to verify membership. Implementing the __iter__() method will result in both if in and for in . If there is a more efficient way to verify membership, do this in __contains__() .

+1
source

Source: https://habr.com/ru/post/1398195/


All Articles