首页 > 编程语言 > 详细

python collections模块中namedtuple()

时间:2017-05-10 17:38:26      阅读:283      评论:0      收藏:0      [点我收藏+]

最近看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()

原文:http://xxuer.blog.51cto.com/11947593/1924122

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!