gpt4 book ai didi

python - `namedtuple` 在 3.5.1 中有什么变化吗?

转载 作者:IT老高 更新时间:2023-10-28 21:51:51 25 4
gpt4 key购买 nike

在 Python 3.5.0 上:

>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster(a=4, b=9)
>>> c
Cluster(a=4, b=9)
>>> vars(c)
OrderedDict([('a', 4), ('b', 9)])

在 Python 3.5.1 上:

>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster(a=4, b=9)
>>> c
Cluster(a=4, b=9)
>>> vars(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute

似乎关于 namedtuple 的某些内容发生了变化(或者可能是关于 vars() 的某些内容?)。

这是故意的吗?难道我们不应该再使用这种模式将命名元组转换为字典了吗?

最佳答案

根据 Python bug #24931 :

[__dict__] disappeared because it was fundamentally broken in Python 3, so it had to be removed. Providing __dict__ broke subclassing and produced odd behaviors.

Revision that made the change

具体来说,没有定义 __slots__ 的子类会表现得很奇怪:

>>> Cluster = namedtuple('Cluster', 'x y')
>>> class Cluster2(Cluster):
pass
>>> vars(Cluster(1,2))
OrderedDict([('x', 1), ('y', 2)])
>>> vars(Cluster2(1,2))
{}

使用 ._asdict().

关于python - `namedtuple` 在 3.5.1 中有什么变化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34166469/

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