繁体   English   中英

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

[英]Python 2: What is the most elegant/pythonic way of doing a enum with string interpretations?

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

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"

fruit = Fruits.APPLE
print fruit.__unicode__()

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

此外,必须有一种更优雅的方式

怎么做得更好?

一对观察:

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

  • 我无法复制您的问题

使用stdlib Enum (3.4+)或enum34 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'

并在使用中:

>>> fruit = Fruits.APPLE
>>> unicode(fruit)
u'Crunchy Apple'

如果您可以使用aenum library 1,您将有更轻松的时间:

from aenum import Enum

class Fruits(Enum, init='value description'):
    APPLE = 'A', 'Crunchy Apple'
    PEAR = 'P', 'Sweet Pear'
    BANANA = 'B', 'Long Banana'
    def describe(self):
        return self.description

并在使用中:

fruit = Fruits.APPLE
fruit.describe()

请注意,由于unicode是Python 3中的默认值,因此我将名称更改为describe


1披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration( aenum库的作者。

enum34模块有你想要的。

from enum import Enum

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

fruit = Fruits.apple

print fruit.value
>> 'A'

使用整数可能更好

from enum import Enum

class Fruits(Enum):
    apple = 1
    pear = 2
    banana = 3

fruit = Fruits.apple

print fruit.value
>> 1

并使用以下方法重新创建对象(例如,从数据库中获取):

fruit = Fruits(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM