您的位置:首页 > 编程语言 > Python开发

python collections模块中namedtuple()

2017-05-10 14:56 459 查看
最近看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