作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 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
具有 x
和 y
属性:
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
请注意,最后一个示例使用的是 aenum
包1。您可以使用 enum34
来完成同样的事情。或通过为 Point
类编写 __init__
来获取 stdlib enum
。
1 披露:我是 Python stdlib Enum
的作者, enum34
backport , 和 Advanced Enumeration (aenum
)图书馆。
关于具有复杂类型的 Python 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37678418/
我是一名优秀的程序员,十分优秀!