根据官方文档:
x[i]
大致等同于type(x).__getitem__(x, i)
。
相较于看似更简单的 x.__getitem__(i)
,上述方式有什么好处呢?
编辑:为什么Python会这样实现?
下面展示一段代码,说明标准行为的一个缺点:最后一个断言失败了,而调用__getitem__
的倒数第二个却通过了。
def poww_bar(base):
class Bar():
def __getitem__(self, x):
return lambda: base**x
return Bar()
def poww_foo(base):
class Foo():
pass
f = Foo()
f.__getitem__ = lambda x: lambda: base ** x
return f
pow_bar2 = poww_bar(2)
pow_foo2 = poww_foo(2)
assert pow_bar2.__getitem__(3)() == 8 # OK
assert pow_bar2[3]() == 8 # OK
assert pow_foo2.__getitem__(3)() == 8 # OK
assert pow_foo2[3]() == 8 # TypeError: 'Foo' object is not subscriptable
f.__getitem__ = ...
是不足以定义索引运算符的。也许当你使用def __getitem__(...): ...
时,解释器会在幕后执行一些魔法,将此函数注册为特殊函数,并有资格使用索引语法糖。 - Alexey Larionovf.__getitem__
版本仅适用于Foo
类的单个实例f
,而不是整个类(它只接受1个参数,与标准版本中的(self, x)
相反)。 - Alexey Larionov