1.namedtuple的用法
python中tuple是一個非常高效的集合對象,但是我們只能通過索引的方式訪問這個集合中的元素。
import collections
Person=collections.namedtuple('Person','name age gender')
print'Type of Person:',type(Person)
Bob=Person(name='Bob',age=30,gender='male')
print'Representation:',Bob
Jane=Person(name='Jane',age=29,gender='female')
print'Field by Name:',Jane.name
for people in[Bob,Jane]:
print"%s is %d years old %s" % people
來解釋一下nametuple的幾個參數,以Person=collections.namedtuple(‘Person’,’name age gender’)爲例,其中’Person’是這個namedtuple的名稱,後面的’name age gender’這個字符串中三個用空格隔開的字符告訴我們,我們的這個namedtuple有三個元素,分別名爲name,age和gender。我們在創建它的時候可以通過Bob=Person(name=’Bob’,age=30,gender=’male’)這種方式,這類似於Python中類對象的使用。而且,我們也可以像訪問類對象的屬性那樣使用Jane.name這種方式訪問namedtuple的元素。其輸出結果如下:
Type of Person: <type 'type'>
Representation: Person(name='Bob', age=30, gender='male')
Field by Name: Jane
Bob is 30 years old male
Jane is 29 years old female
2.Python中模擬enum枚舉類型的5種方法
# way1
class Directions:
up = 0
down = 1
left = 2
right =3
print Directions.down
# way2
dirUp, dirDown, dirLeft, dirRight = range(4)
print dirDown
# way3
import collections
dircoll=collections.namedtuple('directions', ('UP', 'DOWN', 'LEFT', 'RIGHT'))
directions=dircoll(0,1,2,3)
print directions.DOWN
# way4
def enum(args, start=0):
class Enum(object):
__slots__ = args.split()
def __init__(self):
for i, key in enumerate(Enum.__slots__, start):
setattr(self, key, i)
return Enum()
e_dir = enum('up down left right')
print e_dir.down
# way5
# some times we need use enum value as string
Directions = {'up':'up','down':'down','left':'left', 'right':'right'}
print Directions['down']