Python2:使用字符串解释进行枚举的最优雅的/Python方式是什么?

2024-03-28 11:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个带有预定义的单字符常量(适合存储在数据库中)和字符串解释的枚举。我的想法是:

class Fruits(Enum):
    APPLE = 'A'
    PEAR = 'P'
    BANANA = 'B'
    def __unicode__(self):
        if self == APPLE: return "Crunchy Apple"
        if self == PEAR: return "Sweet Pear"
        if self == BANANA: return "Long Banana"

但是

^{pr2}$

给予

AttributeError: 'unicode' object has no attribute '__unicode__'

此外,必须有一种更优雅的方式来做这件事

如何做得更好?在


Tags: 字符串self数据库applereturnifdefunicode
2条回答

enum34模块有您想要的。在

from enum import Enum

class Fruits(Enum):
    apple = 'A'
    pear = 'P'
    banana = 'B'

fruit = Fruits.apple

print fruit.value
>> 'A'

使用整数可能更好

^{pr2}$

如果获得对象的值(例如从数据库中),请使用以下方法重新创建该对象:

^{3}$

一些观察结果:

  • 不应该直接调用__dunder__方法;而是使用匹配的命令:unicode而不是__unicode__

  • 我无法复制您的问题

使用stdlib ^{}(3.4+)或^{} backport(Python 2.x),您必须很难创建自己的基础Enum类:

class EnumWithDescription(Enum):
    def __new__(cls, value, desc):
        member = object.__new__(cls)
        member._value_ = value
        member.description = desc
        return member
    def __unicode__(self):
        return self.description

class Fruits(EnumWithDescription):
    _order_ = 'APPLE PEAR BANANA'   # if using Python 2.x and order matters
    APPLE = 'A', 'Crunchy Apple'
    PEAR = 'P', 'Sweet Pear'
    BANANA = 'B', 'Long Banana'

使用中:

^{pr2}$

如果您可以使用^{}1,您将更轻松地使用它:

^{3}$

使用中:

fruit = Fruits.APPLE
fruit.describe()

注意,由于unicode是Python3中的默认值,所以我将名称改为describe。在


1公开:我是Python stdlib ^{}^{} backport和{a6}库的作者。在

相关问题 更多 >