【发布时间】: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