考虑:
class Item: def __init__(self, a, b): self.a = a self.b = b class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd')
有没有办法使这种简单枚举的思想适应这种情况?(请参阅此问题)理想情况下,就像在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具有新的Enum数据类型(已反向移植为,enum34并增强为aenum1)。无论enum34和aenum2轻松支持您的使用情况:
enum34
aenum
[ aenumpy2 / 3]
import aenum class EnumWithAttrs(aenum.AutoNumberEnum): _init_ = 'a b' GREEN = 'a', 'b' BLUE = 'c', 'd'
[ enum34py2 / 3或stdlib enum3.4+]
stdlib enum
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 stdlibEnum,enum34backport和Advanced Enumeration(aenum) 库的作者。
Enum
2 aenum还支持NamedConstants和基于元类NamedTuples。
NamedConstants
NamedTuples