Redeclaration Of The Method "in" Within A Class
Solution 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:
>>>classBar:...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]
>>>4in b
False
>>>2in 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.
Solution 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__()
.
Post a Comment for "Redeclaration Of The Method "in" Within A Class"