gpt4 book ai didi

python - 覆盖子类 Python 枚举中的方法

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:50 26 4
gpt4 key购买 nike

来自 PEP 435在子类枚举上允许以下内容:

>>> class Foo(Enum):
... def some_behavior(self):
... pass
...
>>> class Bar(Foo):
... happy = 1
... sad = 2
...

假设我想以不同的方式为 happysad 枚举定义 some_behavior

有没有比这样更好的方法:

>>> class Bar(Foo):
... happy = 1
... sad = 2
... def some_behavior(self):
... if self is Bar.happy:
... # happy behavior
... elif self is Bar.sad:
... # sad behavior

这对我来说看起来很笨重。

最佳答案

不,没有。

我的意思是,您也许可以这样做:

def some_behavior(self):
return {Bar.happy: some_function
Bar.sad: some_other_function}[self](arguments?)

或者像这样:

def some_behavior(self):
custom_thing = {Bar.happy: some_function
Bar.sad: some_other_function}[self]
# do something which is the same for both
custom_thing()
# do something else the same for both

但是除非 some_function 等已经存在,否则这可能不会比您现在拥有的更好(尽管我想您可能可以节省一两级缩进)。您可以在此处使用 lambda,但它很快就会变得丑陋,我不推荐它,除非在最简单的情况下(无论如何通常可以用 functools.partial 处理)。

正如评论中所讨论的,您可以做这样的事情:

class Foo(Enum):
happy = 1
sad = 2

def happy_behavior(): # No self argument!
self = Foo.happy # only if you need self
...

def sad_behavior():
self = Foo.sad
...

Foo.happy.some_behavior = happy_behavior
Foo.sad.some_behavior = sad_behavior

在我看来,这相当丑陋,但它应该适用于所有合理的情况,包括像 Foo(1).some_behavior()Foo['sad'] 这样的表达式。一些_行为()。但是,它可能会混淆静态类型检查器和/或 linters。

关于python - 覆盖子类 Python 枚举中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803941/

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