gpt4 book ai didi

Python 3 枚举 : Enum inheriting another Enum doesn't work?

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:43 24 4
gpt4 key购买 nike

我只是想通过引用官方 Python 文档在 Python 3 中创建一个枚举 https://docs.python.org/3.4/library/enum.html尤其是 8.13.13.2 和 8.13.13.4 示例。

我的目标是拥有一个枚举,我可以对其进行迭代、比较并拥有三个独立的属性。但我一直发现这个错误:

AttributeError: can't set attribute

__init__() 构造函数中似乎有错误。

代码:

我首先尝试了一个这样的类:

class Hand(Enum):
FIVE_OF_KIND = (6,'FIVE_OF_KIND',[5])
FOUR_OF_KIND = (5,'FOUR_OF_KIND',[4,1])
FULL_HOUSE = (4,'FULL_HOUSE',[3,2])
THREE_OF_KIND = (3,'THREE_OF_KIND',[3,1,1])
DOUBLE_PAIR = (2,'DOUBLE_PAIR',[2,2,1])
PAIR = (1,'PAIR',[2,1,1,1])
NOTHING = (0,'NOTHING',[1,1,1,1,1])

def __init__(self, val, name, struct):
self.val = val
self.name = name
self.struct = struct

def __ge__(self, other):
if self.__class__ is other.__class__:
return self.value >= other.value
return NotImplemented

def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented

def __le__(self, other):
if self.__class__ is other.__class__:
return self.value <= other.value
return NotImplemented

def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented

然后有两个像这样的类:

class OrderedEnum(Enum):
def __ge__(self, other):
if self.__class__ is other.__class__:
return self.value >= other.value
return NotImplemented

def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented

def __le__(self, other):
if self.__class__ is other.__class__:
return self.value <= other.value
return NotImplemented

def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented


class Hand(OrderedEnum):
FIVE_OF_KIND = (6,'FIVE_OF_KIND',[5])
FOUR_OF_KIND = (5,'FOUR_OF_KIND',[4,1])
FULL_HOUSE = (4,'FULL_HOUSE',[3,2])
THREE_OF_KIND = (3,'THREE_OF_KIND',[3,1,1])
DOUBLE_PAIR = (2,'DOUBLE_PAIR',[2,2,1])
PAIR = (1,'PAIR',[2,1,1,1])
NOTHING = (0,'NOTHING',[1,1,1,1,1])

def __init__(self, val, name, struct):
self.val = val
self.name = name
self.struct = struct

最佳答案

Enum 对象已经有一个 name 属性(例如,参见 8.13.13.3 ),显然你不能设置它——当你认为这是有道理的关于枚举应该如何表现。你可以像这样实现你想要的:

from enum import Enum

class OrderedEnum(Enum):
# Same as your code.

class Hand(OrderedEnum):

FIVE_OF_KIND = (6, [5])
FOUR_OF_KIND = (5, [4,1])
FULL_HOUSE = (4, [3,2])
THREE_OF_KIND = (3, [3,1,1])
DOUBLE_PAIR = (2, [2,2,1])
PAIR = (1, [2,1,1,1])
NOTHING = (0, [1,1,1,1,1])

def __init__(self, val, struct):
# No need to set self.name. It's already handled.
self.val = val
self.struct = struct

for h in Hand:
print((h.name, h.val, h.struct))

关于Python 3 枚举 : Enum inheriting another Enum doesn't work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327057/

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