python2.6新特性named tuple

[size=large]named tuple

Any tuple subclass whose indexable elements are also accessible using named attributes (for example, time.localtime() returns a tuple-like object where the year is accessible either with an index such as t[0] or with a named attribute like t.tm_year).

A named tuple can be a built-in type such as time.struct_time, or it can be created with a regular class definition. A full featured named tuple can also be created with the factory function collections.namedtuple(). The latter approach automatically provides extra features such as a self-documenting representation like Employee(name='jones', title='programmer').

更多文档见
http://acm2008.cct.lsu.edu/localdoc/python/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

官方用法复制
1.Sql
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print emp.name, emp.title

当然,我们可以伟大的山寨一下,自动生成这个EmployeeRecord :)

山寨用法演示
In [115]: def enum(field_names):
.....: t=namedtuple("enum",field_names)
.....: return t._make(range(len(t._fields)))
.....:

In [116]: a=enum("red black yellow")

In [117]: b=enum("zsp psz")

In [118]: a.red
Out[118]: 0

In [119]: a.black
Out[119]: 1

In [120]: b.zsp
Out[120]: 0

In [121]: type(a)
Out[121]: <class '__main__.enum'>

In [122]: type(b)
Out[122]: <class '__main__.enum'>

In [123]: type(a) is type(b)
Out[123]: False


好处? --》collections — High-performance container datatypes

[/size] :arrow:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值