【问题标题】:What is the difference between namedtuple and 'type' functionnamedtuple 和 'type' 函数有什么区别
【发布时间】:2019-10-18 08:18:01
【问题描述】:

我最近访问了一个关于 python 技巧的论坛并遇到了这个:

>>> Points = type("Points", (object,), {'x' : None, 'y' : None})
>>> Player = Points()
>>> Player.x = 23
>>> Player.y = 54
>>> Player.x
23
>>> Player.y - Player.x
31
...

这个语法让我想起了命名元组的语法:

>>> from collections import namedtuple
>>> Points = namedtuple("Points", ['x', 'y'])
>>> Player = Points(
    x = 23,
    y = 54
)
>>> Player.x
23
>>> Player.y - Player.x
21
...

除了命名元组不能更改并且具有索引之外,我无法理解它们有何不同。命名元组和类型函数有什么优势,在我们的项目中使用什么更好?

【问题讨论】:

  • type 是用于在 Python 中构造所有类型(类)的基本元类。 namedtuple 是一个返回具有非常特定行为的类型的函数。我确信它在内部使用type 来完成它的工作,但实际上它就像type 的一个更有限的版本,它只生成某种类。

标签: python namedtuple


【解决方案1】:

让我们深入研究源代码!

首先,我们来看看namedtuple的定义:

result = type(typename, (tuple,), class_namespace)

class_namespace 包含字段名称:

    for index, name in enumerate(field_names):
        doc = _sys.intern(f'Alias for field number {index}')
        class_namespace[name] = _tuplegetter(index, doc)

namedtuple 实质上创建了一个从tuple 派生的对象,而您的第一个示例从基础object 创建了一个对象。

结论

您可以查看this answer 以查看两者之间的内存差异。 您可以根据可读性和您希望与该对象一起使用的其他内容来决定使用哪一个。我想说的是,根据上面的答案,看看你的示例代码,我会选择namedtuple(或者它的typing 版本,它更酷!:

class Employee(NamedTuple):
    name: str
    id: int

)

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多