Skip to content

Instantly share code, notes, and snippets.

@sanpingz
Created May 25, 2013 15:36
Show Gist options
  • Save sanpingz/5649489 to your computer and use it in GitHub Desktop.
Save sanpingz/5649489 to your computer and use it in GitHub Desktop.
模拟Enum
class Animal:
DOG = 1
CAT = 2
assert DOG == 1
assert CAT == 2
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
class Enum(tuple): __getattr__ = tuple.index
from collections import namedtuple
def enum(*keys):
return namedtuple('Enum', keys)(*keys)
# With sequential number values
def enum(*keys):
return namedtuple('Enum', keys)(*range(len(keys)))
# From a dict / keyword args
def enum(**kwargs):
return namedtuple('Enum', kwargs.keys())(*kwargs.values())
def enum(**enums):
'''simple constant "enums"'''
return type('Enum', (object,), enums)
from recordtype import recordtype
def enum(*keys):
return recordtype('Enum', keys)(*keys)
if __name__ == '__main__':
animals = Enum(["DOG", "CAT", "HORSE"])
print animals.DOG
print Animal.DOG
MyEnum = enum('FOO', 'BAR', 'BAZ')
print MyEnum.FOO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment