【发布时间】:2019-04-23 03:27:21
【问题描述】:
假设我有以下内容:
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)时如何让它工作?
【问题讨论】:
-
我强烈建议将其作为
print(Color)以外的其他内容的输出。如果您有print(Color)这样做,那么容易造成混淆。 -
@user2357112 你能概述一个替代解决方案吗?
-
写一个辅助函数,或者一个不是
__str__的类方法。如果你按照你的建议去做,当你试图获得调试输出时,你会得到像print('Object type:', type(thing))打印Object type: The colors are:...这样令人困惑的结果。