python技巧 namedtuple
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)