为什么在Python 3.5中调用__getitem__而在Python 2.7中调用?

时间:2017-02-06 02:02:14

标签: python python-2.7 python-3.x python-3.5 python-internals

我有一个字节子类,提供__getitem__ dunder方法。始终在Python 3.5中调用__getitem__方法,但仅在Python 2.7中调用非切片键。 (相反,似乎父{q} __getitem__已应用于该实例。)为什么会出现这种情况?是否有解决方法?

代码

class A(object):
    def __getitem__(self, key):
        print("in A.__getitem__ with key " + str(key))
        return []

class B(bytes):
    def __getitem__(self, key):
        print("in B.__getitem__ with key " + str(key))
        return []

if __name__ == "__main__":
    import sys
    print(sys.version)

    a = A()
    b = B()

    print("[0]")
    a[0]
    b[0]

    print("[0:1]")
    a[0:1]
    b[0:1]

    print("[:1]")
    a[:1]
    b[:1]

Python 3.5输出

始终调用类定义的__getitem__

(venv) snafu$ python ./x.py
3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609]
[0]
in A.__getitem__ with key 0
in B.__getitem__ with key 0
[0:1]
in A.__getitem__ with key slice(0, 1, None)
in B.__getitem__ with key slice(0, 1, None)
[:1]
in A.__getitem__ with key slice(None, 1, None)
in B.__getitem__ with key slice(None, 1, None)

Python 2.7输出

仅为非切片键调用类定义的__getitem__

(venv2.7) snafu$ python x.py
2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609]
[0]
in A.__getitem__ with key 0
in B.__getitem__ with key 0
[0:1]
in A.__getitem__ with key slice(0, 1, None)
[:1]
in A.__getitem__ with key slice(None, 1, None)

1 个答案:

答案 0 :(得分:6)

Python 2具有__getslice__,如果存在,则优先于__getitem__进行无级切片。这在Python 3中已经消失了。