【问题标题】:Is it possible to assign different enums to same value in Python class?是否可以在 Python 类中将不同的枚举分配给相同的值?
【发布时间】:2022-01-20 07:52:23
【问题描述】:

我想用 Python 编写枚举类。

我的问题是我希望不同的枚举输入具有相同的值。例如:

class Animal(Enum):
    Cat = ['Perian cat', 'Bengal cat', 'Siamese cat']

那么我可以这样使用它:

some_animal = Animal('Persian cat')
print(some_animal)
>> Animal.Cat

我认为这是不可能的,但只是为了确定我想在这里提出这个要求。

更新

我试过这个解决方案:

class _Cat(Enum):
 BENGAL = 'Bengal cat'
 PERSIAN = 'Persian cat'
 SIAMESE = 'Siamese cat'

class Animal(Enum):
 Cat = _Cat

从这个意义上说,我可以访问 Cat 类的值,但我想要实现的是这样的:

some_animal = Animal('Persian cat')
print(some_animal)
>> Animal.Cat.PERSIAN

谢谢。

【问题讨论】:

  • 您想要的可能是一个存储给定名称和相关枚举值(都作为字段)的类。不仅仅是枚举。枚举基本上是一堆单例——即使你要分配一些属性——例如Animal.Cat.something = 'test',然后Animal('Bengal cat').something 也将被设置。因为所有 Animal.Cat 都是同一个对象(is,不仅仅是==
  • 感谢您的评论。你能写一个简短的例子吗?我想我没有完全理解。
  • 我的意思是:创建一个包含两件事的类:你的完整描述和你的枚举

标签: python python-3.x class enums


【解决方案1】:

最简单的方法是使用来自aenumMultiEnum

from aenum import MultiValueEnum

class Animal(MultiValueEnum):
    CAT = 'Cat', 'Persian cat', 'Bengal cat', 'Siamese cat'
    DOG = 'Dog', 'Greyhound', 'Boxer', 'Great Dane'
    def __repr__(self):
        # make the repr not reduntant
        return "<%s.%s>" % (self.__class__.__name__, self.name)

并在使用中:

>>> Animal('Bengal cat')
<Animal.CAT>

>>>> Animal('Boxer')
<Animal.DOG>

如果您需要坚持使用Enum 的stdlib 版本:

from enum import Enum

class Animal(Enum):
    #
    def __new__(cls, *values):
        member = object.__new__(cls)
        member._value_ = values[0]
        member.all_values = values
        return member
    #
    @classmethod
    def _missing_(cls, value):
        for member in cls:
            if value in member.all_values:
                return member
    #
    CAT = 'Cat', 'Persian cat', 'Bengal cat', 'Siamese cat'
    DOG = 'Dog', 'Greyhound', 'Boxer', 'Great Dane'
    def __repr__(self):
        # make the repr not reduntant
        return "<%s.%s>" % (self.__class__.__name__, self.name)

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

【讨论】:

    【解决方案2】:

    您可以使用功能 API 获得关闭结果。事实上,困难的部分是不具有多个具有相同值的成员,而是具有包含空格的名称(即:不能是标识符):

    Animal = Enum('Animal', (('Persian cat', 'cat'), ('Bengal cat', 'cat'),
                             ('Siamese cat', 'cat')))
    

    那么你可以这样做:

    >>> print(Animal['Persian cat'].value)
    cat
    

    并且可以控制成员的平等:

    >>>Animal['Persian cat'] == Animal['Bengal cat']
    True
    

    但是你的枚举类变得非常接近普通的dict。如果您还打算添加新成员,那么恕我直言,这暗示您想要的不是Enum,而是简单的dict

    【讨论】:

    • 感谢您的回复。如果我没有空格,例如persian_cat, bengal_cat 等,我可以写一个类,这样我也可以在途中编辑类方法吗?我认为功能 API 是不可能的。简单的场景:我按照我描述的方式上课,但另外,如果我放一个在课堂上没有描述的 Enum,我可以用它做点什么。
    • @JustPawel:您确定dict 不能更好地满足您的需求吗? (看看我的编辑...)
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 2020-10-08
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    相关资源
    最近更新 更多