如果您希望 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
最后,如果您只需要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
请注意,最后一个示例是使用 aenum 包1。您可以通过为Point 类编写__init__ 来使用enum34 或stdlib enum 完成同样的事情。
1 披露:我是Python stdlib Enum、enum34 backport 和Advanced Enumeration (aenum) 库的作者。