python namedtuple
2015-07-13 19:04
585 查看
python standard library介绍了一个叫做namedtuple的东西:
这段代码的两点在type(Person),输出为:
type of Person: <class 'type'>
也就是相当于添加了这样一段定义:
class Person(object):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
Person是一个动态生成的类型。
最重要的是,除了像结构体那样可以按field访问之外,它还能像一般的元组那样按索引访问。Person还是元组的子类。
对于习惯C语言中结构体童鞋来说,这个可以说是最好的替代品!
__author__ = 'sfesly' import collections Person = collections.namedtuple('Person', 'name age gender') print('type of Person: %s' % (type(Person))) bob = Person(name='Bob', age =30, gender='male') print('\nRepresentation:%s' % (str(bob))) jane = Person(name='Jane', age=29,gender='female') print('\nField by name:%s' % (jane.name)) for p in [bob, jane]: print ('%s is a %d year old %s' % p) print(bob[2])
这段代码的两点在type(Person),输出为:
type of Person: <class 'type'>
也就是相当于添加了这样一段定义:
class Person(object):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
Person是一个动态生成的类型。
最重要的是,除了像结构体那样可以按field访问之外,它还能像一般的元组那样按索引访问。Person还是元组的子类。
对于习惯C语言中结构体童鞋来说,这个可以说是最好的替代品!
相关文章推荐
- Python--处理文献中单词,统计个数
- python程序(scrapy爬虫)在windows环境下开机定时自启动
- python requests的安装与简单运用
- Python 安装 pip package
- python简单获取数组元素个数的方法
- Python3 - 时间处理与定时任务
- python连接字符串的方法小结
- Python装饰器学习(九步入门)
- Hive中使用Python实现Transform时遇到Broken pipe错误排查
- python基础教程总结2——字符串
- CIFAR数据库预处理 (python)
- python_1(基础知识)
- python第三方库系列之二十--批量机器配置管理库SaltStack
- Python程序的创建步骤
- python mysql
- python中的set集合操作
- python 运行时报错误SyntaxError: Non-ASCII character '\xe5' in file 1.py on line 2
- python3.4学习笔记(二十二) python 在字符串里面插入指定分割符,将list中的字符转为数字
- python第三方库系列之十九--python测试使用的mock库
- python基础教程总结1——列表和元组