为什么python中的namedtuple需要一个名称? [英] Why does namedtuple in python need a name?

查看:143
本文介绍了为什么python中的namedtuple需要一个名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们要为 namedtuple 提起名字 Card ,如下所示?

Why do we need to mention the name Card for namedtuple like below?

import collections

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

我认为一张简单的 Card = collections.namedtuple(['rank','suit' ])实际上可以起到相同的作用吗?

I think a simple Card = collections.namedtuple(['rank', 'suit']) can actually give the same effect right?

例如,我可以在dict这样的字典中获得相同的信息:

For example I can have the same information in a dict like:

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


推荐答案

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

No, that won't give the same effect.


collections.namedtuple
返回一个新的元组子类名为typename ...

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

namedtuple 返回子类

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

The name parameter specifies the class name of the new subclass, just as you would define a regular Python class and give it a name:

>>> 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))
    ...

快速类型检查会清除所有疑问:

A quick type check clears every doubt:

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

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

So there, you have namedtuple, a factory function that returns a subclass of a tuple.

这篇关于为什么python中的namedtuple需要一个名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆