I am trying to understand how to implement a list or a hash of objects in Python. More specifically, in this question, which was the closest I could get, I saw that by doing:
class MyClass(object):
def __init__(self):
self.numbers = [1,2,3,4,54]
def __contains__(self, key):
return key in self.numbers
>>> m = MyClass()
>>> 54 in m
True
I could use the operator in directly on the class to check an attribute inside of it.
My question is an extension of this one. Suppose I have a list or a hash of MyClass objects, that is:
list = [m1,m2,m3]
hash = {m1,m2,m3}
I would like to use something like:
if 54 in list:
#do something
if 54 in hash:
#do something
What methods are necessary to be defined in MyClass so that the in operator works? I am unsure what in does (if is it a == that would require an __eq or something else). If you happen to know how one would make .index() work in such case I would appreciate as well.
Edit: Sorry the initial question was confusing. I hope I made it clear. I am trying to find an attribute that is part of the class, such as the original example of the other question. But now I am trying to do so inside a list or a hash. In a sense, I would like that by asking if an element is inside a list, it asks if it is inside each element of the list. I am unsure if by using the operator in on a list or a hash it does that, or it compares using ==.
Thank you.