python枚举与属性 [英] python enums with attributes
问题描述
考虑:
class Item:
def __init__(self, a, b):
self.a = a
self.b = b
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
有没有办法使简单的枚举的想法适应这种情况? (请参阅此问题)理想情况下,作为在Java中,我想把它全部归入一个类。
Is there a way to adapt the ideas for simple enums to this case? (see this question) Ideally, as in Java, I would like to cram it all into one class.
Java模型:
enum EnumWithAttrs {
GREEN("a", "b"),
BLUE("c", "d");
EnumWithAttrs(String a, String b) {
this.a = a;
this.b = b;
}
private String a;
private String b;
/* accessors and other java noise */
}
推荐答案
Python 3.4有一个新的枚举数据类型(已 backported as enum34
和增强为 aenum
1 )。 enum34
和 aenum
2 轻松支持您的用例:
Python 3.4 has a new Enum data type (which has been backported as enum34
and enhanced as aenum
1). Both enum34
and aenum
2 easily support your use case:
[ aenum
py2 / 3]
[aenum
py2/3]
import aenum
class EnumWithAttrs(aenum.AutoNumberEnum):
_init_ = 'a b'
GREEN = 'a', 'b'
BLUE = 'c', 'd'
[ enum34
py2 / 3或 stdlib枚举
3.4 +]
[enum34
py2/3 or stdlib enum
3.4+]
import enum
class EnumWithAttrs(enum.Enum):
def __new__(cls, *args, **kwds):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def __init__(self, a, b):
self.a = a
self.b = b
GREEN = 'a', 'b'
BLUE = 'c', 'd'
正在使用:
--> EnumWithAttrs.BLUE
<EnumWithAttrs.BLUE: 1>
--> EnumWithAttrs.BLUE.a
'c'
1 披露:我是 Python stdlib的作者枚举
, enum34
backport 和高级枚举( aenum
)库。
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
2 aenum
还支持
NamedConstants
和基于元类的 NamedTuples
。
这篇关于python枚举与属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!