如何重载operator`in`?

时间:2016-09-21 00:57:01

标签: python python-3.x operator-overloading operators grammar

如何在我定义的类中使用in作为运算符__getitem__的前提下,重载运算符[]

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]

如何使用in这样实现该功能?

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

2 个答案:

答案 0 :(得分:1)

in运算符将调用__contains__魔法。 见https://docs.python.org/2/reference/datamodel.html#object.contains

答案 1 :(得分:0)

如果您尝试,则无需这样做:

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

它会像你想要的那样返回True