python3.3pep418示例给出了“namespace”对象不是iterab

2024-05-29 04:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

python3.3的beta版发布了,非常棒。在

新修改的time模块使用get_clock_info方法来获取有关平台的许多逻辑时钟的信息。PEP 418描述新的时间模块。在

当我尝试运行PEP 418中引用的一个示例程序clock_resolution.py时,我在下面第54行得到TypeError: 'namespace' object is not iterable

46 clocks = ['clock', 'perf_counter', 'process_time']
47 if hasattr(time, 'monotonic'):
48     clocks.append('monotonic')
49 clocks.append('time')
50 for name in clocks:
51     func = getattr(time, name)
52     test_clock("%s()" % name, func)
53     info = time.get_clock_info(name)
54     if 'precision' in info:
55         print("- announced precision: %s" % format_duration(info['precision']))
56     print("- implementation: %s" % info['implementation'])
57     print("- resolution: %s" % format_duration(info['resolution']))

第53行的“info”包含:

^{pr2}$

那么如何迭代命名空间对象呢?在


Tags: 模块nameininfogetiftimepep
1条回答
网友
1楼 · 发布于 2024-05-29 04:55:45

你不想迭代对象;你只想测试属性的存在。两种方式:

# "easier to get forgiveness than permission" approach
try:
    print(info.precision)
except AttributeError:
    pass

# "look before you leap" approach
if hasattr(info, "precision"):
    print(info.precision)

in测试用于检查字典、列表、元组或其他序列中是否有内容。在一般情况下,in将尝试迭代某个值(dict和{}是例外;Python的特殊情况是为了提高效率)。但是info是一个不支持迭代的类的实例。在

如果你愿意,你可以这样做:

^{pr2}$

属性实际上存储在dict实例成员变量中,名为.__dict__。在

编辑:@DSM写了一篇评论,显示了上述的另一种选择。内置函数vars()将返回.__dict__成员变量,因此这等同于上述内容:

# nicer alternate "look before you leap"
if "precision" in vars(info):
    print(info.precision)

相关问题 更多 >

    热门问题