假设我有以下内容:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
作为print(Color)
的输出,我想看看:
The colors are:
- RED
- GREEN
- BLUE
我尝试过:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
@classmethod
def __str__(self):
res = "The colors are:\n"
for g in set(map(lambda c: c.name, Color)):
res += '- ' + g + '\n'
return res
但是它只能用作print(Color(1))
。使用print(Color)
时如何使用?
答案 0 :(得分:7)
要覆盖 class 的打印,可以在 metaclass 上定义__str__
:
from enum import Enum, EnumMeta
class MyEnumMeta(EnumMeta):
def __str__(cls):
lines = [f"The {cls.__name__.lower()}s are:"]
for member in cls:
lines.append(f"- {member.name}")
return '\n'.join(lines)
class Color(Enum, metaclass=MyEnumMeta):
RED = 1
GREEN = 2
BLUE = 3
演示:
>>> Color
<enum 'Color'>
>>> print(Color)
The colors are:
- RED
- GREEN
- BLUE
>>> Color.RED
<Color.RED: 1>
>>> print(Color.RED)
Color.RED
发现了类名:
>>> class Animal(Enum, metaclass=MyEnumMeta):
... cat = 'meow'
... dog = 'woof'
... badger = 'grrr'
...
>>> print(Animal)
The animals are:
- cat
- dog
- badger