gpt4 book ai didi

python - 创建抽象枚举类

转载 作者:太空狗 更新时间:2023-10-29 17:48:19 24 4
gpt4 key购买 nike

我正在尝试使用抽象方法创建一个抽象枚举(实际上是 Flag)。我的最终目标是能够基于我定义的基本枚举创建复合枚举的字符串表示形式。我能够在不将类抽象化的情况下获得此功能。

这是基本的 Flag 类和一个示例实现:

from enum import auto, Flag

class TranslateableFlag(Flag):
@classmethod
def base(cls):
pass

def translate(self):
base = self.base()
if self in base:
return base[self]
else:
ret = []
for basic in base:
if basic in self:
ret.append(base[basic])
return " | ".join(ret)

class Students(TranslateableFlag):
ALICE = auto()
BOB = auto()
CHARLIE = auto()
ALL = ALICE | BOB | CHARLIE

@classmethod
def base(cls):
return {Students.ALICE: "Alice", Students.BOB: "Bob",
Students.CHARLIE: "Charlie"}

一个例子用法是:

((Students.ALICE | Students.BOB).translate())
[Out]: 'Alice | Bob'

由于 MetaClass 冲突,切换到 TranslateableFlag(Flag, ABC) 失败。(我没看懂这篇文章 - Abstract Enum Class using ABCMeta and EnumMeta,所以我不确定它是否在回答我的问题)。

我想以某种方式获得这样的功能:

@abstractclassmethod
@classmethod
def base(cls):
pass

这有可能实现吗?

最佳答案

以下是调整 accepted answer 的方法问题Abstract Enum Class using ABCMeta and EnumMeta创建你想要的那种抽象 Enum 类:

from abc import abstractmethod, ABC, ABCMeta
from enum import auto, Flag, EnumMeta


class ABCEnumMeta(ABCMeta, EnumMeta):

def __new__(mcls, *args, **kw):
abstract_enum_cls = super().__new__(mcls, *args, **kw)
# Only check abstractions if members were defined.
if abstract_enum_cls._member_map_:
try: # Handle existence of undefined abstract methods.
absmethods = list(abstract_enum_cls.__abstractmethods__)
if absmethods:
missing = ', '.join(f'{method!r}' for method in absmethods)
plural = 's' if len(absmethods) > 1 else ''
raise TypeError(
f"cannot instantiate abstract class {abstract_enum_cls.__name__!r}"
f" with abstract method{plural} {missing}")
except AttributeError:
pass
return abstract_enum_cls


class TranslateableFlag(Flag, metaclass=ABCEnumMeta):

@classmethod
@abstractmethod
def base(cls):
pass

def translate(self):
base = self.base()
if self in base:
return base[self]
else:
ret = []
for basic in base:
if basic in self:
ret.append(base[basic])
return " | ".join(ret)


class Students1(TranslateableFlag):
ALICE = auto()
BOB = auto()
CHARLIE = auto()
ALL = ALICE | BOB | CHARLIE

@classmethod
def base(cls):
return {Students1.ALICE: "Alice", Students1.BOB: "Bob",
Students1.CHARLIE: "Charlie"}


# Abstract method not defined - should raise TypeError.
class Students2(TranslateableFlag):
ALICE = auto()
BOB = auto()
CHARLIE = auto()
ALL = ALICE | BOB | CHARLIE

# @classmethod
# def base(cls):
# ...

结果:

Traceback (most recent call last):
...
TypeError: cannot instantiate abstract class 'Students2' with abstract method 'base'

关于python - 创建抽象枚举类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56131308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com