1

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
pillravi
  • 4,035
  • 5
  • 19
  • 33
fuyangzhen
  • 23
  • 4

2 Answers2

1

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

Peter Shinners
  • 3,686
  • 24
  • 24
0

No need for that, if you try:

"second" in ["first", "second"]

it is going to return True just as you want

Adil Baaj
  • 21
  • 4