Python的namedtuple使用详解

来源:互联网 发布:紫猫编程学院全套教程 编辑:程序博客网 时间:2024/05/17 09:21

Python的namedtuple使用详解

namedtuple是继承自tuple的子类。namedtuple创建一个和tuple类似的对象,而且对象拥有可访问的属性。

下面看个列子

from collections import namedtuple# 定义一个namedtuple类型User,并包含name,sex和age属性。User = namedtuple('User', ['name', 'sex', 'age'])# 创建一个User对象user = User(name='kongxx', sex='male', age=21)# 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法user = User._make(['kongxx', 'male', 21])print user# User(name='user1', sex='male', age=21)# 获取用户的属性print user.nameprint user.sexprint user.age# 修改对象属性,注意要使用"_replace"方法user = user._replace(age=22)print user# User(name='user1', sex='male', age=21)# 将User对象转换成字典,注意要使用"_asdict"print user._asdict()# OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

转载请以链接形式标明本文地址 
本文地址:http://blog.csdn.net/kongxx/article/details/51553362

原创粉丝点击