在 Python 中,我可以使用 typename 定义命名元组吗?

In Python, can I define a named tuple using typename?

我想知道为什么 代码段 B 中的第三行会触发错误。我的理解是在片段 B(和 A)的第二行,我创建了一个 class 变量(不是 class 实例)cls_obj 其 type/class 名称是 Duck.就像

class Duck(...):
    ...Code goes here

cls_obj=Duck

所以我希望代码段 A 和 B 都能正常工作,但是代码段 B 失败了!出了什么问题?

# Snippet A
from collections import namedtuple
cls_obj=namedtuple('Duck', 'bill tail')
duck = cls_obj(bill='wide orange', tail='long')

# Snippet B
from collections import namedtuple
cls_obj=namedtuple('Duck', 'bill tail')
duck = Duck(bill='wide orange', tail='long')

在Python中,class只是一种特殊的值。

class Duck(object):
    pass

# 'Duck' is just a variable, you can change it
Duck = 3

x = Duck() # Fails!

您可以这样做:

>>> class Goat(object):
...     def __repr__(self):
...         return 'Goat()'
...
>>> Cow = Goat
>>> del Goat
>>> Goat()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Goat' is not defined
>>> Cow()
Goat()
>>> Cow.__name__
'Goat'
>>> Cow().__class__
<class '__main__.Goat'>

现在您明白了 class 只是一个值,一切都会开始变得更有意义了。 namedtuple('Goat', ...)class Goat 不同。它定义了一个 class 但没有将 结果值 (class 本身)分配给全局范围内的变量。函数做不到,namedtuple()是普通函数。