我有一个字节子类,提供__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]
始终调用类定义的__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)
仅为非切片键调用类定义的__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)