fuyangzhen fuyangzhen - 2 months ago 10
Python Question

How to overload operator `in`?

How can I overload operator

in
on the premise that I have used
__getitem__
for operator
[]
in the class I defined?

class myClass:
def __init__(self):
self.slots = [None]*5

def __setitem__(self, key, data):
self.set(key, data)

def __getitem__(self,key):
return self.get(key)

def set(self, key, data):
self.slots[key]=data

def get(self,key):
return self.slots[key]

s=myClass()
s[0]='first'
s[1]='second'
print(s[0])#<-------first
print(s.slots)#<----['first', 'second', None, None, None]


How can I implement the function with
in
like that?

print(('second' in s))#<----True
print(('third' in s))#<-----False

Answer

The in operator will call to the __contains__ magic method. See https://docs.python.org/2/reference/datamodel.html#object.contains