Python 如何在`中重载运算符`?

Python 如何在`中重载运算符`?,python,python-3.x,operator-overloading,operators,grammar,Python,Python 3.x,Operator Overloading,Operators,Grammar,如果我已经在我定义的类中为操作符[]使用了\uuu getitem\uuu,我如何在中重载操作符 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)

如果我已经在我定义的类中为操作符
[]
使用了
\uuu getitem\uuu
,我如何在中重载操作符

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]

中的
操作符将调用
\uuuuu包含\uuuu
魔术方法。
请参见

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

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

它会像你想的那样返回真值

太棒了!你的回答是如此迅速、高效和准确!!谢谢你!!!
"second" in ["first", "second"]