【问题标题】:Python __getitem__ behaviour across different versionsPython __getitem__ 跨不同版本的行为
【发布时间】: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


【解决方案1】:

看起来存在于 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,看看是否可以在那里重现。

【讨论】:

  • 适用于 Windows 上的 Python 2.7.4(32 位)。
  • 正如我在问题中提到的,它在 Windows 上的 2.7.8 上产生相同的结果。唯一的异常是在 python 2.7.6
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 2011-09-25
  • 1970-01-01
  • 2012-08-17
  • 2015-05-30
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多