gpt4 book ai didi

跨不同版本的 Python __getitem__ 行为

转载 作者:太空狗 更新时间:2023-10-30 01:38:08 28 4
gpt4 key购买 nike

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 中,slice 对象试图获取实例的长度,以便它可以将 '-1' 转换为实际值。例如,如果实例的长度为 10,则输出将为“slice(0, 9, None)”。

这种行为看起来很奇怪。谁能验证我的观察是否正确?如果是,那么这背后有任何官方文件吗?我们如何应对这种行为以在所有 python 版本上支持我们的项目?

最佳答案

看起来 2.7.3 和 2.7.8 之间存在一个错误

Python 2.7.8 (default, Jul  1 2014, 17:30:21) 
[GCC 4.9.0 20140604 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def __getitem__(self, item):
... print item
...
>>> a = A()
>>> a[0:-1]
slice(0, -1, None)

对比

Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... def __getitem__(self, item):
... print item
...
>>> a = A()
>>> a[0:-1]
slice(0, -1, None)

它可能在 Windows 上。在 Windows 上尝试 2.7.8,看看是否可以在那里重现。

关于跨不同版本的 Python __getitem__ 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051750/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com