【问题标题】:How to override the [] operator in Python?如何覆盖 Python 中的 [] 运算符?
【发布时间】:2010-12-29 18:58:06
【问题描述】:

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

【问题讨论】:

    标签: python operator-overloading


    【解决方案1】:

    您需要使用__getitem__ method

    class MyClass:
        def __getitem__(self, key):
            return key * 2
    
    myobj = MyClass()
    myobj[3] #Output: 6
    

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        编辑

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

        http://docs.python.org/reference/datamodel.html中都有记录

        【讨论】:

        • __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 slice, i.e.: if isinstance(arg, slice): ...
        最近更新 更多