我最近访问了一个带有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
...
我不明白它们之间的区别,除了命名元组不能更改并具有索引。元组和类型函数的命名有哪些优势?在我们的项目中最好使用哪些优势?
答案 0 :(得分:0)
让我们深入研究源代码!
首先,我们来看看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
)