Considerar:
class Item: def __init__(self, a, b): self.a = a self.b = b class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd')
¿Hay una manera de adaptar las ideas para enums simples para este caso? (vea esta pregunta ) Idealmente, como en Java, me gustaría agruparlo todo en una clase.
Modelo de 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 tiene un nuevo tipo de datos Enum (que ha sido enum34
como enum34
y mejorado como aenum
1 ). Tanto enum34
como aenum
2 son compatibles con su caso de uso:
[ aenum
/ 3]
import aenum class EnumWithAttrs(aenum.AutoNumberEnum): _init_ = 'ab' GREEN = 'a', 'b' BLUE = 'c', 'd'
[ enum34
/ 3 o 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'
Y en uso:
--> EnumWithAttrs.BLUE --> EnumWithAttrs.BLUE.a 'c'
1 Divulgación: Soy el autor de Python stdlib Enum
, el enum34
backport y la biblioteca de enumeración avanzada ( aenum
) .
2 aenum
también admite NamedConstants
y NamedTuples
basado en NamedTuples
.
Utilice un timbre nombrado
from collections import namedtuple Item = namedtuple('abitem', ['a', 'b']) class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd')
Para Python 3:
class Status(Enum): READY = "ready", "I'm ready to do whatever is needed" ERROR = "error", "Something went wrong here" def __new__(cls, *args, **kwds): obj = object.__new__(cls) obj._value_ = args[0] return obj # ignore the first param since it's already set by __new__ def __init__(self, _: str, description: str = None): self._description_ = description def __str__(self): return self.value # this makes sure that the description is read-only @property def description(self): return self._description_
Y puede usarlo como una enumeración estándar o fábrica por tipo:
print(Status.READY) # ready print(Status.READY.description) # I'm ready to do whatever is needed print(Status("ready")) # this does not create a new object # ready