python中的collections.namedtuple

简介

collections.namedtuple是一个工厂方法,它可以动态的创建一个继承tuple的子类。跟tuple相比,返回的子类可以使用名称来访问元素。

使用方法

用一个例子来介绍:

>>> from collections import namedtuple
>>> Account = namedtuple("Account", ["name","pwd"]) ①
>>> account = Account(*("bingyang", "123456"))  ②
>>> account.name
'bingyang'
>>> account.pwd
'123456'

①创建一个名称为Account的类,该类拥有两个属性namepwd,将这个类赋值给变量Account
②调用这个类,并传递属性的值。 值的顺序要跟定义属性的顺序一致,或者是使用另外一种方式: Account(name='bingyang', pwd='123456')

nametuple一共支持4个参数:def namedtuple(typename, field_names, verbose=False, rename=False)

typename

类名称

field_names

字段名称。
它的值可以是一个能保证元素间顺序不变的可遍历对象或者是逗号链接起来的字符串,例如:

>>> Account = namedtuple("Account", ("name", "pwd"))
>>> Account = namedtuple("Account", "name,pwd")

verbose

设置为True的话会打印出类的定义代码。

>>> Account = namedtuple("Account", "name,pwd", verbose=True)
class Account(tuple):
    'Account(name, pwd)'

    __slots__ = ()

    _fields = ('name', 'pwd')

    def __new__(_cls, name, pwd):
        'Create new instance of Account(name, pwd)'
        return _tuple.__new__(_cls, (name, pwd))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Account object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Account(name=%r, pwd=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Account object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('name', 'pwd'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    name = _property(_itemgetter(0), doc='Alias for field number 0')

    pwd = _property(_itemgetter(1), doc='Alias for field number 1')


>>> 

rename

默认情况下,namedtuple会检查我们传递的属性名称是否符合规范,对于不符合规范的名称会抛出异常。当我们设置rename为异常时,将会对不符合规范的名称设置为_$d$d的值为属性设置时候的index),例如:

>>> Account = namedtuple("Account", ['1','2'],  rename=True)
>>> account = Account('bingyang', '123456')
>>> account._0
'bingyang'
>>> account._1
'123456'

总结

namedtuple的主要作用是将代码与它所控制的元素位置解耦。所以在一些比较大的元组列表中,我们可以将元祖转为namedtuple使用,这样就算元祖增加了新的列,代码也不会崩溃。而且使用名称来访问数据,代码可读性也比较高。

原文地址:https://www.cnblogs.com/jiangbingyang/p/7455853.html