Python 2.7 Python 2.7、enum34和enum属性的用户友好unicode表示

Python 2.7 Python 2.7、enum34和enum属性的用户友好unicode表示,python-2.7,enums,python-unicode,Python 2.7,Enums,Python Unicode,我在Python 2.7中使用enum34向数据库写入不同的选项(使用Flask和Flask Admin),enum如下所示: class Veggie(enum.Enum): celery = 1 tomato = 2 broccoli = 3 然后,我按如下方式使用它来指定值作为选项: my_veggie = Veggie.celery 我使用整数是因为我希望它以整数的形式存储在数据库中 但是,当我将其输出给最终用户时,unicode(Veggie.cellery

我在Python 2.7中使用enum34向数据库写入不同的选项(使用Flask和Flask Admin),enum如下所示:

class Veggie(enum.Enum):
    celery = 1
    tomato = 2
    broccoli = 3
然后,我按如下方式使用它来指定值作为选项:

my_veggie = Veggie.celery
我使用整数是因为我希望它以整数的形式存储在数据库中

但是,当我将其输出给最终用户时,unicode(Veggie.cellery)将给出以下字符串:Veggie.cellery,但我希望它是一个用户友好的字符串,例如“Veggie:cellery”、“Veggie:Tomato”等。。。。显然,我可以操纵unicode()返回的字符串,但我怀疑应该有一种更简单、更干净的方法,使用类方法或enum内置的东西来实现这一点


谢谢,

如果您想更改
Enum
类的字符串输出,只需添加您自己的
\uuu str\uu
方法:

class Veggie(Enum):
    celery = 1
    tomato = 2
    broccoli = 3
    def __str__(self):
       return self.__class__.__name__ + ': ' + self.name

>>> Veggie.tomato
<Veggie.tomato: 2>
>>> print Veggie.tomato
Veggie: tomato
并从中继承:

class Veggie(PrettyEnum):
    celery = 1
    tomato = 2
    broccoli = 3

如果要更改
Enum
类的字符串输出,只需添加自己的
\uuuu str\uuu
方法:

class Veggie(Enum):
    celery = 1
    tomato = 2
    broccoli = 3
    def __str__(self):
       return self.__class__.__name__ + ': ' + self.name

>>> Veggie.tomato
<Veggie.tomato: 2>
>>> print Veggie.tomato
Veggie: tomato
并从中继承:

class Veggie(PrettyEnum):
    celery = 1
    tomato = 2
    broccoli = 3