【问题标题】:What's the common practice for enums in Python? [duplicate]Python中枚举的常见做法是什么? [复制]
【发布时间】:2010-10-16 17:07:41
【问题描述】:

可能重复:
How can I represent an 'enum' in Python?

Python 中枚举的常见做法是什么? IE。它们是如何在 Python 中复制的?

public enum Materials
{
    Shaded,
    Shiny,
    Transparent,
    Matte
}

【问题讨论】:

标签: python enums


【解决方案1】:
class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

【讨论】:

  • 我没见过那个,好东西。
  • @Joan 你可以做_unused, Shaded, Shiny, Transparent, Matte = range(5)
  • 有点晚了,但如果你不喜欢_unused,你也可以使用Shaded, Shiny, Transparent, Matte = range(1, 5)
  • 不幸的是,这种制作枚举的方法是不完整的,因为枚举不能被迭代,每个值也不是唯一的类型(例如,只是一个 int)。
  • 这应该被更新以添加 enums 在 Python 3.4 中
【解决方案2】:

我已经多次看到这种模式:

>>> class Enumeration(object):
        def __init__(self, names):  # or *names, with no .split()
            for number, name in enumerate(names.split()):
                setattr(self, name, number)

>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2

您也可以只使用班级成员,但您必须提供自己的编号:

>>> class Foo(object):
        bar  = 0
        baz  = 1
        quux = 2

>>> Foo.quux
2

如果您正在寻找更健壮的东西(稀疏值、特定于枚举的异常等),try this recipe

【讨论】:

    【解决方案3】:

    我不知道为什么 Python 不支持枚举。 我发现模拟它们的最佳方法是覆盖 _ str _ 和 _ eq _ 以便您可以比较它们,当您使用 print() 时,您会得到字符串而不是数值。

    class enumSeason():
        Spring = 0
        Summer = 1
        Fall = 2
        Winter = 3
        def __init__(self, Type):
            self.value = Type
        def __str__(self):
            if self.value == enumSeason.Spring:
                return 'Spring'
            if self.value == enumSeason.Summer:
                return 'Summer'
            if self.value == enumSeason.Fall:
                return 'Fall'
            if self.value == enumSeason.Winter:
                return 'Winter'
        def __eq__(self,y):
           return self.value==y.value
    

    用法:

    >>> s = enumSeason(enumSeason.Spring)
    
    >>> print(s)
    
    Spring
    

    【讨论】:

    【解决方案4】:

    你也许可以使用继承结构,虽然我玩得越多,我就越觉得脏。

    class AnimalEnum:
      @classmethod
      def verify(cls, other):
        return issubclass(other.__class__, cls)
    
    
    class Dog(AnimalEnum):
      pass
    
    def do_something(thing_that_should_be_an_enum):
      if not AnimalEnum.verify(thing_that_should_be_an_enum):
        raise OhGodWhy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 2011-06-09
      • 2016-10-02
      • 1970-01-01
      • 2012-07-08
      相关资源
      最近更新 更多