gpt4 book ai didi

具有复杂类型的 Python 枚举

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

我是 Python 的新手,我想知道我是否可以构建具有复杂结构的枚举,而不仅仅是原始类型。例如(伪代码):

Point::Enum
x, y
constructor ( x, y ) {
...
}

bottom_left = Point ( 0, 0 )
top_left = Point ( 0, 100 )
top_right = Point ( 100, 100 )
bottom_right = Point ( 100, 0 )

到目前为止,我只能找到提到带有字符串或整数的枚举的 Python 文档。

最佳答案

如果您希望 Point 作为跟踪角点的 Enum 的独立实体,那么您需要将它们分开:

from enum import Enum

class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point(%r, %r)' % (self.x, self.y)

class Corner(Enum):
BottomLeft = Point(0, 0)
TopLeft = Point(0, 100)
TopRight = Point(100, 100)
BottmRight = Point(100, 0)

这样做意味着每个 enum 包含一个 Point 作为它的值,但不是 Point 本身:

>>> Corner.BottomLeft
<Corner.BottomLeft: Point(0, 0)>
>>> Corner.BottomLeft.value
Point(0, 0)

如果您希望enum 成员一个Point,那么在Point 类中混合:

from enum import Enum

class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point(%r, %r)' % (self.x, self.y)

class Corner(Point, Enum):
BottomLeft = 0, 0
TopLeft = 0, 100
TopRight = 100, 100
BottmRight = 100, 0

>>> Corner.TopLeft
<Corner.TopLeft: (0, 0)>
>>> isinstance(Corner.TopLeft, Point)
True
>>> Corner.TopLeft.value
(0, 100)
>>> Corner.TopLeft.x
0
>>> Corner.TopLeft.y
100

最后,如果您只需要让 enum 具有 xy 属性:

from aenum import Enum

class Corner(Enum):
__init__ = 'x y'
BottomLeft = 0, 0
TopLeft = 0, 100
TopRight = 100, 100
BottmRight = 100, 0

>>> Corner.TopLeft
<Corner.TopLeft: (0, 100)>
>>> Corner.TopLeft.value
(0, 100)
>>> Corner.TopLeft.x
0
>>> Corner.TopLeft.y
100

请注意,最后一个示例使用的是 aenum1。您可以使用 enum34 来完成同样的事情。或通过为 Point 类编写 __init__ 来获取 stdlib enum


1 披露:我是 Python stdlib Enum 的作者, enum34 backport , 和 Advanced Enumeration (aenum)图书馆。

关于具有复杂类型的 Python 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37678418/

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