创建一个具有可初始化属性的成员的枚举

问题描述 投票:0回答:1

这个答案我学会了如何创建带有属性的枚举(即附加数据):

from typing import NamedTuple

class EnumAttr(NamedTuple):
  data: str


class EnumWithAttrs(EnumAttr, Enum):
    GREEN = EnumAttr(data="hello")
    BLUE = EnumAttr(data="world")

EnumWithAttrs.GREEN.data
"hello"

我现在要做以下事情:

EnumWithAttrs.BLUE(data="yellow").data
'yellow'

换句话说:我希望能够执行以下操作:

a = EnumWithAttrs.BLUE(data="yellow")
b = EnumWithAttrs.BLUE(data="red")

我尝试了以下方法(及其各种变体),但它不起作用:

from enum import Enum
from typing import Any, Callable, NamedTuple, Self

class EnumAttr(NamedTuple):
  data: str = ""

class EnumWithAttrs(EnumAttr, Enum):
    GREEN = EnumAttr(data="hello")
    BLUE = EnumAttr()

    def with_data(self, s: str) -> Self:
       self._replace(data=s)
       return self

x = EnumWithAttrs.BLUE.with_data("world")
x.data
''
python enums
1个回答
0
投票

您是否正在尝试使用一个可调用的枚举来返回

EnumAttrs
实例的值?

from enum import Enum
from typing import NamedTuple


class EnumAttr(NamedTuple):
    data: str

    @classmethod
    def with_data(cls, data):
        return cls(data)

class EnumWithAttrs(EnumAttr, Enum):
    GREEN = EnumAttr(data="hello")
    BLUE = EnumAttr(data='world')

    def __call__(self, data):
        return self.value.with_data(data)
© www.soinside.com 2019 - 2024. All rights reserved.