Python-namedtuple,enum 逃离我推掉我的手 2022-07-14 13:56 104阅读 0赞 ### 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']
还没有评论,来说两句吧...