基于Python Enum 类构建(使用 tostring fromstring)
class Enum(object):
@classmethod
def tostring(cls, val):
for k,v in vars(cls).iteritems():
if v==val:
return k
@classmethod
def fromstring(cls, str):
return getattr(cls, str.upper(), None)
@classmethod
def build(cls, str):
for val, name in enumerate(str.split()):
setattr(cls, name, val)
class MyEnum(Enum):
VAL1, VAL2, VAL3 = range(3)
class YourEnum(Enum):
CAR, BOAT, TRUCK = range(3)
class MoreEnum(Enum):
pass
print MyEnum.fromstring('Val1')
print MyEnum.tostring(2)
print MyEnum.VAL1
print YourEnum.BOAT
print YourEnum.fromstring('TRUCK')
# Dodgy semantics for creating enums.
# Should really be
# MoreEnum = Enum.build("CIRCLE SQUARE")
MoreEnum.build("CIRCLE SQUARE")
print MoreEnum.CIRCLE
print MoreEnum.tostring(1)
print MoreEnum.tostring(MoreEnum.CIRCLE)
编辑添加了构建类方法,以便可以使用字符串来构建枚举。
尽管那里可能有更好的解决方案。