python2.6新特性named tuple

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

你可能感兴趣的:(html,sql,python,performance)