The Enum
class is rather special since it turns every attribute of the derived class into an enum value, including any dictionary that you would define at the class level.
But defining it at the module level is possible; let's use double underscore and all-caps to indicate that it's a private constant:
class Suit(Enum):
Clubs, Diamonds, Hearts, Spades = range(1, 5)
def __str__(self):
return __DSHORTSUIT[self]
__DSHORTSUIT = {Suit.Clubs: 'c', Suit.Diamonds: 'd', Suit.Hearts: 'h', Suit.Spades: 's'}
Note that __DSHORTSUIT
must be defined after Suit
, otherwise it won't be able to access its members yet.
An alternative (which you may or may not like, depending on your use case) is to use the strings as enum values directly:
class Suit(Enum):
Clubs = 'c'
Diamonds = 'd'
Hearts = 'h'
Spades = 's'
def __str__(self):
return self.value
If you want to keep the values as integers but add the string version as an additional property on those objects, you can use some higher-level enum voodoo using a custom __new__
:
class Suit(Enum):
Clubs = 'c'
Diamonds = 'd'
Hearts = 'h'
Spades = 's'
def __new__(cls, short_str):
obj = object.__new__(cls)
obj._value_ = len(cls.__members__) + 1
obj.short_str = short_str
return obj
def __str__(self):
return self.short_str