gpt4 book ai didi

python - 为什么 namedtuple 模块不使用元类来创建 nt 类对象?

转载 作者:IT老高 更新时间:2023-10-28 20:47:24 26 4
gpt4 key购买 nike

我花了一些时间调查 collections.namedtuple module几周前。该模块使用工厂函数将动态数据(新的 namedtuple 类的名称和类属性名称)填充到一个非常大的字符串中。然后 exec 以字符串(代表代码)为参数执行,并返回新的类。

有谁知道为什么要这样做,当有一种现成的用于这种东西的特定工具时,即元类?我自己没有尝试过,但似乎 namedtuple 模块中发生的所有事情都可以使用 namedtuple 元类轻松完成,如下所示:

class namedtuple(type):

等等等等

编辑:谦虚地建议阅读the answer I wrote several years later ,在页面下方。

最佳答案

issue 3974 中有一些提示.作者提出了一种创建命名元组的新方法,但被拒绝并给出以下评论:

It seems the benefit of the original version is that it's faster, thanks to hardcoding critical methods. - Antoine Pitrou

There is nothing unholy about using exec. Earlier versions used other approaches and they proved unnecessarily complex and had unexpected problems. It is a key feature for named tuples that they are exactly equivalent to a hand-written class. - Raymond Hettinger

另外,这里是the original namedtuple recipe的描述部分:

... the recipe has evolved to its current exec-style where we get all of Python's high-speed builtin argument checking for free. The new style of building and exec-ing a template made both the __new__ and __repr__ functions faster and cleaner than in previous versions of this recipe.

如果您正在寻找一些替代实现:

关于python - 为什么 namedtuple 模块不使用元类来创建 nt 类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184531/

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