如何理解python中的枚举?

时间:2019-03-21 13:50:26

标签: python python-3.x

这是一个相当简单的问题。我试图理解定义枚举类的两种不同方式。以下是代码。

class AnimalEnum(Enum):
      HORSE = 1
      COW = 2
      CHICKEN = 3
      DOG = 4

AnimalEnum2 = Enum('Animal', 'HORSE COW CHICKEN DOG')



def main1():
    print(AnimalEnum.CHICKEN, "\n")
    print(repr(AnimalEnum.CHICKEN), "\n")
    print("get the name and value of some Enum members:", "\n")
    print("name:", AnimalEnum.CHICKEN.name,"\n")
    print("value:",AnimalEnum.CHICKEN.value,"\n")
    for animal in AnimalEnum:
        print('Name: {} Value: {} \n'.format(animal, animal.value))  

    for a in AnimalEnum2:
        print('Name: {} Value: {} \n'.format(a,a.value))   

    for animal in AnimalEnum:
        print("animal:", animal, "\n")
        print("type of animal:", type(animal), "\n") 

    for a in AnimalEnum2:
        print("a:", a, "\n")
        print("type of a:", type(a), "\n")  # type of a: <enum 'Animal'>     



main1()

我了解这段代码的输出。我唯一令人困惑的部分是,对于此AnimalEnum2 = Enum('Animal', 'HORSE COW CHICKEN DOG')AnimalEnum2Animal之间到底有什么区别?

1 个答案:

答案 0 :(得分:0)

其中一个是枚举Animal类型,另一个是枚举AnimalEnum类型。

这里的知识:

  1. 使用auto编号方案进行枚举
  2. 通过auto编号使用功能API表单编号
  3. 您的AnimalEnum枚举使用手动编号

使用Enum的Functional API具有以下结果:

The second argument is the source of enumeration member names. 
It can be a whitespace-separated string of names, a sequence of 
names, a sequence of 2-tuples with key/value pairs, or a mapping 
(e.g. dictionary) of names to values. The last two options 
enable assigning arbitrary values to enumerations; the others 
auto-assign increasing integers starting with 1

这是您在Animal中所做的,而在AnimalEnum中,您只是显式地命名了关联的值。

至于实际使用情况,由于所有值均相等,因此它们在实际使用中基本上是等效的