【问题标题】:Python enums with complex types具有复杂类型的 Python 枚举
【发布时间】:2016-06-07 11:41:52
【问题描述】:

我是 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 文档。

【问题讨论】:

  • 对类型没有限制,而且在 Python 中字符串和整数是“复杂类型”。
  • Python 中没有原始类型
  • 好吧,没有,但是 1 或 'blah' 与 (0,0) 有很大不同 :-)

标签: python enums complextype


【解决方案1】:

如果您希望 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 具有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。您可以通过为Point 类编写__init__ 来使用enum34 或stdlib enum 完成同样的事情。


1 披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration (aenum) 库的作者。

【讨论】:

    【解决方案2】:

    试试这个:

    class Point(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    class Enum:
        bottom_left = Point(0, 0)
        top_left = Point(0, 100)
        top_right = Point(100, 100)
        bottom_right = Point(100, 0)
    

    【讨论】:

      【解决方案3】:

      您可以将它们声明为全局变量,例如 BOTTOM_LEFTTOP_LEFTTOP_RIGHTBOTTOM_RIGHT

      您可能知道,与其他语言(C++、Java)不同,Python 没有,您只需声明它,不要更改它(绅士游戏)

      然而,Alex Martelli 的 recipe 可以方便地在 Python 中模拟 const

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 2020-07-18
        • 2016-10-02
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多