python技巧 namedtuple

丁壯發表於2018-11-16

python的namedtuple可以建立一個帶欄位名的元祖和一個帶名字的類

 

In [1]: from collections import namedtuple
   ...:
   ...: nginx=namedtuple(`nginx`,[`active`,`accepts`,`handled`,`requests`,`reading`,`writing`,`waiting`])
   ...:

In [2]: get_nginx=nginx(1,2,3,4,11,111,22)

In [3]: get_nginx.active
Out[3]: 1

In [4]: get_nginx
Out[4]: nginx(active=1, accepts=2, handled=3, requests=4, reading=11, writing=111, waiting=22)

 

namedtuple的幾個屬性

    _fields 類屬性
    _make(iterable) 類方法
    _asdict() 例項方法

In [7]: nginx._fields
Out[7]: (`active`, `accepts`, `handled`, `requests`, `reading`, `writing`, `waiting`)

In [8]: get_nginx._asdict()
Out[8]:
OrderedDict([(`active`, 1),
             (`accepts`, 2),
             (`handled`, 3),
             (`requests`, 4),
             (`reading`, 11),
             (`writing`, 111),
             (`waiting`, 22)])
             
             

In [12]: new_nginx=(1,2,3,4,5,6,7)

In [13]: new=nginx._make(new_nginx)

In [14]: new
Out[14]: nginx(active=1, accepts=2, handled=3, requests=4, reading=5, writing=6, waiting=7)   

相關文章