问题描述
考虑:
类项目:def __init__(self, a, b):self.a = a自我.b = b类项目:绿色 = 项目('a','b')蓝色 = 项目('c', 'd')
有没有办法使简单枚举的想法适应这种情况?(参见这个问题)理想情况下,如在 Java 中,我想把它全部塞进一个类中.
Java 模型:
enum EnumWithAttrs {绿色(a",b"),蓝色(c",d");EnumWithAttrs(String a, String b) {this.a = a;this.b = b;}私人字符串a;私人字符串 b;/* 访问器和其他 Java 噪声 */}
Python 3.4 有一个 新的枚举数据类型(已被反向移植为enum34
和 增强为 aenum
).enum34
和 aenum
都可以轻松支持您的用例:
[aenum
py2/3]
导入枚举类 EnumWithAttrs(aenum.AutoNumberEnum):_init_ = 'a b'绿色 = 'a', 'b'蓝色 = 'c', 'd'
[enum34
py2/3 或 stdlib enum
3.4+]
导入枚举类 EnumWithAttrs(enum.Enum):def __new__(cls, *args, **kwds):值 = len(cls.__members__) + 1obj = object.__new__(cls)obj._value_ = 值返回对象def __init__(self, a, b):self.a = a自我.b = b绿色 = 'a', 'b'蓝色 = 'c', 'd'
并在使用中:
-->EnumWithAttrs.BLUE<EnumWithAttrs.BLUE: 1>-->EnumWithAttrs.BLUE.a'C'
披露:我是 Python stdlib 的作者Enum
,enum34
向后移植a> 和 高级枚举 (aenum
) 库.>
aenum
还支持 NamedConstants
和基于元类的 NamedTuples
.
Consider:
class Item:
def __init__(self, a, b):
self.a = a
self.b = b
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
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 model:
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 has a new Enum data type (which has been backported as enum34
and enhanced as aenum
). Both enum34
and aenum
easily support your use case:
[aenum
py2/3]
import aenum
class EnumWithAttrs(aenum.AutoNumberEnum):
_init_ = 'a b'
GREEN = 'a', 'b'
BLUE = 'c', 'd'
[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'
And in use:
--> EnumWithAttrs.BLUE
<EnumWithAttrs.BLUE: 1>
--> EnumWithAttrs.BLUE.a
'c'
Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.
aenum
also supports NamedConstants
and metaclass-based NamedTuples
.
这篇关于带有属性的python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!