簡介
collections.namedtuple
是一個工廠方法,它可以動態的創建一個繼承tuple
的子類。跟tuple
相比,返回的子類可以使用名稱來訪問元素。
使用方法
用一個例子來介紹:
>>> from collections import namedtuple
>>> Account = namedtuple("Account", ["name","pwd"]) ①
>>> account = Account(*("bingyang", "123456")) ②
>>> account.name
'bingyang'
>>> account.pwd
'123456'
①創建一個名稱為Account
的類,該類擁有兩個屬性name
和pwd
,將這個類賦值給變量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
使用,這樣就算元祖增加了新的列,代碼也不會崩潰。而且使用名稱來訪問數據,代碼可讀性也比較高。