Python 中枚举的常见做法是什么?

发布于 2024-07-16 07:54:57 字数 80 浏览 2 评论 0原文

如何在 Python 中实现枚举类型(在某些语言中拼写为 enum)? 获得此功能的常见做法是什么?

How can I implement an enumeration type (spelled enum in some languages) in Python? What is the common practice to get this functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

や莫失莫忘 2024-07-23 07:54:57
class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

更新:对于 Python 3.4+:

从 Python 3.4+ 开始,您现在可以使用 Enum (或 IntEnum 对于具有 int 值的枚举) enum 模块。 使用 enum.auto 来自动增加值:

import enum


class Materials(enum.IntEnum):
    Shaded = 1
    Shiny = enum.auto()
    Transparent = 3
    Matte = enum.auto()


print(Materials.Shiny == 2)  # True
print(Materials.Matte == 4)  # True
class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3

Update: For Python 3.4+:

As of Python 3.4+, you can now use Enum (or IntEnum for enums with int values) from the enum module. Use enum.auto to increment the values up automatically:

import enum


class Materials(enum.IntEnum):
    Shaded = 1
    Shiny = enum.auto()
    Transparent = 3
    Matte = enum.auto()


print(Materials.Shiny == 2)  # True
print(Materials.Matte == 4)  # True
遗弃M 2024-07-23 07:54:57

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

>>> 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

如果您正在寻找更健壮的东西(稀疏值、特定于枚举的异常等), 尝试这个食谱

I've seen this pattern several times:

>>> 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

You can also just use class members, though you'll have to supply your own numbering:

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

>>> Foo.quux
2

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

凉城 2024-07-23 07:54:57

我不知道为什么 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

I have no idea why Enums are not support natively by Python.
The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

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

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring
魄砕の薆 2024-07-23 07:54:57

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

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

You could probably use an inheritance structure although the more I played with this the dirtier I felt.

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文