考虑:
class Item:
def __init__(self, a, b):
self.a = a
self.b = b
class Items:
GREEN = Item('a', 'b')
BLUE = Item('c', 'd')
有没有办法使简单枚举的思想适应这种情况?(请参见this question)理想情况下,就像在Java中一样,我希望将其全部塞进一个类中。
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有一个new Enum data type(已经backported as ^{} 和enhanced as ^{} 1)。
enum34
和aenum
2都很容易支持您的用例:[
aenum
py2/3][
enum34
py2/3或stdlib enum
3.4+]使用中:
1披露:我是Python stdlib ^{} 、^{} backport 和Advanced Enumeration (^{}) 库的作者。
2
aenum
还支持NamedConstants
和基于元类的NamedTuples
。对于Python 3:
并且可以按类型将其用作标准枚举或工厂:
使用namedtuple:
相关问题 更多 >
编程相关推荐