【问题标题】:How to overload operator `in`? [duplicate]如何重载运算符`in`? [复制]
【发布时间】:2017-01-29 01:51:47
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    没必要,如果你尝试:

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

    它会按照你的意愿返回 True

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 太棒了!你的答案是如此迅速,高效和准确!谢谢你!!!
      猜你喜欢
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      相关资源
      最近更新 更多