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


Answers:


290

您需要使用__getitem__方法

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

myobj = MyClass()
myobj[3] #Output: 6

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

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

63

要完全重载它,您还需要实现__setitem____delitem__方法。

编辑

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

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


67
__getslice__, __setslice__`和__delslice__' have been deprecated for the last few releases of ver 2.x (not sure exactly when), and are no longer supported in ver 3.x. Instead, use __getitem__ . __setitem__`和__delitem__' and test if the argument is of type 切片, i.e.: 如果isinstance(阿根廷,片):...
唐·奥唐奈

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.