} } }

    Python: Enum列举的实现

    添加时间:2013-5-31 点击量:

          从C系说话过来用Python,十分艰苦适应了写代码不打花括号,忽然有一天发明它居然木有列举……于是stackoverflow了一把,发明神人的列举(enum)实现处处都是,于是汉化总结过来。

    若是是新版Python用户(Python 3.4 with PEP 435):

     enum import Enum
    
    Animal = Enum(Animal, ant bee cat dog)


     



    or



    class Animals(Enum):
    
    ant = 1
    bee = 2
    cat = 3
    dog = 4


     



    旧版Python用户可以充沛阐扬动态说话的优胜性来机关列举,有简单的:



    def enum(enums):
    
    return type(Enum, (), enums)

    Numbers = enum(ONE=1, TWO=2, THREE=three)
    # Numbers.ONE == 1, Numbers.TWO == 2 and Numbers.THREE == three


     



    有错杂的:



    def enum(sequential, named):
    
    enums = dict(zip(sequential, range(len(sequential))), named)
    return type(Enum, (), enums)

    Numbers = enum(ZERO, ONE, TWO)
    # Numbers.ZERO == 0 and Numbers.ONE == 1


     



    有带值到名称映射的:



    def enum(sequential, named):
    
    enums = dict(zip(sequential, range(len(sequential))), named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums[reverse_mapping] = reverse
    return type(Enum, (), enums)

    # Numbers.reverse_mapping[three] == THREE


     



    有效set实现的:



    class Enum(set):
    
    def __getattr__(self, name):
    if name in self:
    return name
    raise AttributeError

    Animals = Enum(["DOG", "CAT", "HORSE"])
    print Animals.DOG


     



    有效range实现的:



    dog, cat, rabbit = range(3)
    

    # or

    class Stationary:
    (Pen, Pencil, Eraser) = range(0, 3)
    print Stationary.Pen


     



    有效tuple实现的:



    class Enum(tuple): __getattr__ = tuple.index
    

    State = Enum([Unclaimed, Claimed])
    print State.Claimed


     



    有效namedtuple实现的:



     collections import namedtuple
    

    def enum(keys):
    return namedtuple(Enum, keys)(keys)

    MyEnum = enum(FOO, BAR, BAZ)

    # 带字符数字映射的,像C/C++
    def enum(keys):
    return namedtuple(Enum, keys)(range(len(keys)))

    # 带字典映射的,可以映射出各类类型,不局限于数字
    def enum(kwargs):
    return namedtuple(Enum, kwargs.keys())(kwargs.values())
    读书,不要想着实用,更不要有功利心。读书只为了自身的修养。邂逅一本好书如同邂逅一位知己,邂逅一个完美之人。有时心生敬意,有时怦然心动。仿佛你心底埋藏多年的话,作者替你说了出来,你们在时光深处倾心相遇的一瞬间,情投意合,心旷神怡。
    分享到: