gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:42:21 25 4
gpt4 key购买 nike

我创建了一个子类 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/

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