Skip to main content
 首页 » 编程设计

python之为什么python中的namedtuple需要一个名字

2025年05月04日15dflying

为什么我们需要像下面那样为 namedtuple 提及名称 Card?

import collections 
 
Card = collections.namedtuple('Card', ['rank', 'suit']) 

我认为一个简单的 Card = collections.namedtuple(['rank', 'suit']) 实际上可以产生相同的效果,对吗?

例如,我可以在字典中包含相同的信息,例如:

card = dict({'rank': 'A', 'suit': 'spade'}) 

请您参考如下方法:

不,那不会产生相同的效果。

collections.namedtuple: Returns a new tuple subclass named typename...

namedtuple 返回元组类型的子类,而不是元组实例。

name 参数指定新子类的类名,就像您定义一个常规 Python 类并为其命名一样:

>>> from collections import namedtuple 
>>> namedtuple('Card', ['rank', 'suit'], verbose=True) 
class Card(tuple): 
    'Card(rank, suit)' 
 
    __slots__ = () 
 
    _fields = ('rank', 'suit') 
 
    def __new__(_cls, rank, suit): 
        'Create new instance of Card(rank, suit)' 
        return _tuple.__new__(_cls, (rank, suit)) 
    ... 

快速类型检查消除了所有疑问:

>>> type(_), issubclass(_, tuple) 
(<class 'type'>, True)  

因此,您有了 namedtuple,一个返回元组子类的工厂函数。