[英]Python 2: What is the most elegant/pythonic way of doing a enum with string interpretations?
I want a enum with predefined single character constants (good for storing in database) and string interpretation. 我想要一个带有预定义单字符常量的枚举(适合存储在数据库中)和字符串解释。 Here is what I am thinking of: 这是我在想的:
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"
But 但
fruit = Fruits.APPLE
print fruit.__unicode__()
gives 给
AttributeError: 'unicode' object has no attribute '__unicode__'
And besides there must be a more elegant way of doing it 此外,必须有一种更优雅的方式
How to do it better? 怎么做得更好?
A couple observations: 一对观察:
You shouldn't call __dunder__
methods directly; 你不应该直接调用__dunder__
方法; instead use the matching command: unicode
instead of __unicode__
而是使用匹配命令: unicode
而不是__unicode__
I am unable to duplicate your problem 我无法复制您的问题
Using the stdlib Enum
(3.4+) or the enum34
backport (Python 2.x) you will have to do it the hard way -- make your own base Enum
class: 使用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'
and in use: 并在使用中:
>>> fruit = Fruits.APPLE
>>> unicode(fruit)
u'Crunchy Apple'
If you can use the aenum library
1 you will have an easier time of it: 如果您可以使用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
and in use: 并在使用中:
fruit = Fruits.APPLE
fruit.describe()
Note that since unicode
is the default in Python 3 I changed the name to describe
. 请注意,由于unicode
是Python 3中的默认值,因此我将名称更改为describe
。
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport , and the Advanced Enumeration ( aenum
) library. 1披露:我是Python stdlib Enum
, enum34
backport和Advanced Enumeration( aenum
)库的作者。
The enum34 module has what you want. enum34模块有你想要的。
from enum import Enum
class Fruits(Enum):
apple = 'A'
pear = 'P'
banana = 'B'
fruit = Fruits.apple
print fruit.value
>> 'A'
Possibly even better is using integers 使用整数可能更好
from enum import Enum
class Fruits(Enum):
apple = 1
pear = 2
banana = 3
fruit = Fruits.apple
print fruit.value
>> 1
And recreate the object if you get it's value (from a database for instance) using: 并使用以下方法重新创建对象(例如,从数据库中获取):
fruit = Fruits(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.