如何在Python中覆盖[]运算符?

Sah*_*has 194 python operator-overloading

[]在Python中覆盖类的运算符(下标表示法)的方法名称是什么?

Dav*_*ebb 252

您需要使用该__getitem__方法.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6
Run Code Online (Sandbox Code Playgroud)

如果您要设置值,您也需要实现该__setitem__方法,否则会发生这种情况:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
Run Code Online (Sandbox Code Playgroud)


Dav*_*rby 56

要完全超载它,您还需要实现__setitem____delitem__方法.

编辑

我差点忘了......如果你想完全模仿一个列表,你也需要__getslice__, __setslice__ and __delslice__.

所有文档都记录在http://docs.python.org/reference/datamodel.html中

  • `__getslice __,`__ setslice__`和`__delslice__'已被弃用于ver 2.x的最后几个版本(不确定何时),并且在3.x版中不再支持.相反,使用`__getitem__`.`__setitem__`和`__delitem__'并测试参数是否为`slice`类型,即:`if isinstance(arg,slice):... (59认同)

Con*_*ion 14

您正在寻找该__getitem__方法.请参阅http://docs.python.org/reference/datamodel.html,第3.4.6节