Python: Enum枚举的实现
Python: Enum枚举的实现

Python: Enum枚举的实现
• 发表于 2年前
• 阅读 2423
• 收藏 1
• 评论 0

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

#or

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

``````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'
``````

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

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

``````dog, cat, rabbit = range(3)

#or

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

``````class Enum(tuple): __getattr__ = tuple.index

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

``````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())
``````

×