你可以制作一个像这样简单的元类:
class MetaEnum(type):
def __new__(cls, class_name, parents, attrs):
def __init__(self, name=None):
if name is not None: self.name = name
attrs['__init__'] = __init__
Klass = type.__new__(cls, class_name, parents, attrs)
if 'instances' in attrs:
for name in attrs['instances']:
setattr(Klass, name.capitalize(), Klass(name))
del Klass.instances # clean up
return Klass
class Fruit(object):
__metaclass__ = MetaEnum
instances = ('apple', 'banana', 'cranberry')
for attr_name in dir(Fruit):
if not attr_name.startswith('_'):
attr = getattr(Fruit, attr_name)
if type(attr) is Fruit:
print('Fruit.{}, is a Fruit named {}'.format(attr_name, getattr(attr, 'name')))
else:
print('Fruit.{}, is a {}'.format(attr, type(attr)))
输出:
Fruit.Apple, is a Fruit named apple
Fruit.Banana, is a Fruit named banana
Fruit.Cranberry, is a Fruit named cranberry