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

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

What is the name of the method to override the [] operator (subscript notation) for a class in Python?


回答 0

您需要使用__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__'

You need to use the __getitem__ method.

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

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

And if you’re going to be setting values you’ll need to implement the __setitem__ method too, otherwise this will happen:

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

回答 1

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

编辑

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

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

To fully overload it you also need to implement the __setitem__and __delitem__ methods.

edit

I almost forgot… if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__.

There are all documented in http://docs.python.org/reference/datamodel.html


回答 2

您正在寻找__getitem__方法。参见http://docs.python.org/reference/datamodel.html第3.4.6节

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。