zak*_*mck 6 python enums complextype
我是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 )
Run Code Online (Sandbox Code Playgroud)
到目前为止,我只能找到提到字符串或整数的枚举的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)
Run Code Online (Sandbox Code Playgroud)
这样做意味着每个都enum包含一个Pointas作为其值,但不是一个Point本身:
>>> Corner.BottomLeft
<Corner.BottomLeft: Point(0, 0)>
>>> Corner.BottomLeft.value
Point(0, 0)
Run Code Online (Sandbox Code Playgroud)
如果你想enum成员是 a 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
Run Code Online (Sandbox Code Playgroud)
最后,如果您需要的是enums具有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
Run Code Online (Sandbox Code Playgroud)
请注意,最后一个示例使用的是aenum包1.你可以通过为类编写一个enum34或者stdlib 来完成同样的事情.enum__init__Point
1披露:我是Python stdlibEnum,enum34backport和Advanced Enumeration(aenum) 库的作者.