1. 程式人生 > >python collections模塊中namedtuple()

python collections模塊中namedtuple()

ansible

最近看Ansible API中引用了collections的namedtuple()

網上搜了一番後,發現是一個集合模塊,提供了多種集合類。

In [1]: from collections import 
              Callable        Hashable        Mapping         namedtuple      ValuesView      _field_template _itemgetter     
              Container       ItemsView       MappingView     OrderedDict     _abcoll         _get_ident      _repeat         
              Counter         Iterable        MutableMapping  Sequence        _chain          _heapq          _repr_template  
              defaultdict     Iterator        MutableSequence Set             _class_template _imap           _starmap        
              deque           KeysView        MutableSet      Sized           _eq             _iskeyword      _sys

提供了這些方法


本著用到哪裏學哪裏的原則,就來看看這個namedtuple()

In [1]: from collections import namedtuple

In [2]: Option = namedtuple(‘Option‘,[‘user‘,‘password‘])

In [3]: option = Option(‘zhangsan‘,‘123‘)

In [4]: option.user
Out[4]: ‘zhangsan‘

In [5]: option.password
Out[5]: ‘123‘

In [6]: option
Out[6]: Option(user=‘zhangsan‘, password=‘123‘)


就是定義了元組,讓元組可以通過屬性的方式;Ansible模板中自帶的例子中,引用的就可以很明了的看到參數

本文出自 “隔壁老張” 博客,轉載請與作者聯系!

python collections模塊中namedtuple()