Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redeclaration of the method "in" within a class

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,

like image 937
lpostula Avatar asked Dec 12 '22 05:12

lpostula


2 Answers

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.

like image 65
Rik Poggi Avatar answered Dec 27 '22 00:12

Rik Poggi


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__().

like image 20
Janne Karila Avatar answered Dec 27 '22 00:12

Janne Karila