python - 子类的 __getitem__ 返回意外的切片

标签 python python-2.7 subclass slice

我创建了一个子类 ConfigParser.SafeConfigParser 来实现无节配置文件。我遇到的问题是,与我期望 __getitem__ 响应的方式相比,我得到了一个意外的切片类型:

import ConfigParser

class foo(ConfigParser.SafeConfigParser):
    def __getitem__(self, option):
        return option

class bar(object):
    def __getitem__(self,option):
        return option

a = foo()
b = bar()
print a[:]
print b[:]

它的回答让我感到困惑,因为我得到:

slice(0, 2147483647, None)
slice(None, None, None)

在这两种情况下,我都期望 (None, None, None)。我可以猜测它的行为很熟悉——例如,如果我正在使用一个简单的 list() 切片操作——但这​​使得确定用户的意图变得特别困难通过 if option.start is None,在前一种情况下失败。

SafeConfigParser 的哪一部分正在改变这种行为,我该怎么做才能收到 (None, None, None) 而不是 (0, sys.maxint , 无)

最佳答案

SafeConfigParser 是一个旧式类,因此您的 foo 也是。您的 bar 是一个新样式类(派生自 object)。

>>> type(ConfigParser.SafeConfigParser)
<type 'classobj'>

>>> type(foo)
<type 'classobj'>

>>> type(bar)
<type 'type'>

旧式类(class)与新式类(class)有许多不同之处;显然,这是其中之一,大概是为了向后兼容(即因为这就是切片过去的行为方式)。它与 SafeConfigParser 本身无关, 正如您在此处看到的:

class baz:    # old-style class in Python 2.x where x >= 2
    def __getitem__(self, option):
        return option

c = baz()
print c[:]    # slice(0, 2147483647, None)

要解决这个问题,我想您可以尝试更新 ConfigParser 以使用新式类。这可能相当容易;与 Python 3 的 configparser(它不使用旧式类,因为 Python 3 中没有这样的东西)的差异可能会有所帮助。

关于python - 子类的 __getitem__ 返回意外的切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17752424/

相关文章:

python - 在 Python 中使用管道文件描述符时如何检查 EOF?

python - 为相似名词创建空间知识库

python - str.__getslice__ 没有按预期工作,负停止

java - Java中的继承和识别对象类型

python - 如何使用 Python 中的 fonttools 将 woff2 字体转换为 ttf?

python - 索引/多重索引内的字符串替换

swift - 更改 uiview 子类中 CGPoint 线的颜色

java - 声明子类对象

python - 检查通过 python cmd 模块传递的参数

python - pip 和 easy_install 安装 python 包的麻烦