gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:33 24 4
gpt4 key购买 nike

为什么我们需要像下面那样为 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,一个返回元组子类的工厂函数

关于python - 为什么python中的namedtuple需要一个名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42691769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com