【发布时间】:2014-07-31 05:58:16
【问题描述】:
class A(object):
def __getitem__(self, item):
print item
a = A()
a[0:-1]
在 Windows 上的 python 2.7.3、2.7.7、2.7.8、3.3.2 上的输出:
slice(0, -1, None)
win 32 上 python 2.7.6(32 位)的输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute '__len__'
在 python 2.7.6 中,切片对象尝试获取实例的长度,以便将“-1”转换为实际值。例如,如果实例的长度为 10,则输出将为 'slice(0, 9, None)'。
这种行为看起来很奇怪。谁能验证我的观察是否正确?如果是,那么这背后是否有任何官方文件?我们如何应对这种行为以支持我们在所有版本的 python 上的项目?
【问题讨论】:
-
如果是这种情况,那么它看起来像一个错误(他们可能在 python2.7.8 中修复了......)
标签: python python-2.7 magic-methods