Python: Enum枚舉的實現


如果是新版Python用戶(Python 3.4 with PEP 435):

?
1
2
from enum import Enum
Animal = Enum( 'Animal' , 'ant bee cat dog' )

 

or

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

 

舊版Python用戶可以充分發揮動態語言的優越性來構造枚舉,有簡單的:

?
1
2
3
4
5
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'

 

有復雜的:

?
1
2
3
4
5
6
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

 

有帶值到名稱映射的:

?
1
2
3
4
5
6
7
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實現的:

?
1
2
3
4
5
6
7
8
class Enum( set ):
     def __getattr__( self , name):
         if name in self :
             return name
         raise AttributeError
 
Animals = Enum([ "DOG" , "CAT" , "HORSE" ])
print Animals.DOG

 

有用range實現的:

?
1
2
3
4
5
6
7
dog, cat, rabbit = range ( 3 )
 
# or
 
class Stationary:
     (Pen, Pencil, Eraser) = range ( 0 , 3 )
print Stationary.Pen

原文:http://www.cnblogs.com/codingmylife/archive/2013/05/31/3110656.html

有用tuple實現的:

?
1
2
3
4
class Enum( tuple ): __getattr__ = tuple .index
 
State = Enum([ 'Unclaimed' , 'Claimed' ])
print State.Claimed

 

有用namedtuple實現的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from 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())


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM