【问题标题】:Nice print of python Enumpython枚举的漂亮打印
【发布时间】: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:...这样令人困惑的结果。

标签: python enums metaclass


【解决方案1】:

要覆盖的打印,您可以在元类上定义__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

【讨论】:

  • 非常好的解决方案
  • @wim 这看起来像我所追求的。在EnumMeta 周围寻找一些文档得到的信息很少。你能指出任何参考资料吗?
  • 文档中的信息似乎很少,但 the EnumMeta source code 的评论很好。
  • 我看到了,但还是比较神秘。
  • 不需要关于 EnumMeta 的特定文档 - Python 是一种非常一致的语言,这正是元类的工作方式 - “类”在不用于创建新实例时,只是一个普通的 Python 对象,因此,它的 __str____repr__ 将由它自己的类控制。在这种情况下,这个类是 EnumMeta。对于普通类,它是type
猜你喜欢
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多