Вы можете переопределить Enum.__new__
, чтобы принять аргумент doc
следующим образом:
class DocEnum(Enum):
def __new__(cls, value, doc=None):
self = object.__new__(cls) # calling super().__new__(value) here would fail
self._value_ = value
if doc is not None:
self.__doc__ = doc
return self
, который может использоваться как:
class Color(DocEnum):
""" Some colors """
RED = 1, "The color red"
GREEN = 2, "The color green"
BLUE = 3, "The color blue. These docstrings are more useful in the real example"
, который в IPython дает следующее:
In [17]: Color.RED?
Type: Color
String form: Color.RED
Docstring: The color red
Class docstring: Some colors
Это также можно сделать для IntEnum
:
class DocIntEnum(IntEnum):
def __new__(cls, value, doc=None):
self = int.__new__(cls, value) # calling super().__new__(value) here would fail
self._value_ = value
if doc is not None:
self.__doc__ = doc
return self