Use of Python enumerated types

Enumeration types were added to the Python standard library in Python 3.4.

Create enum

Python provides two methods to create enumerations:

  • Create enumeration based on class syntax
  • Create enumeration based on Function API

To create an enumeration, first import the Enum class

>>> from enum import Enum

Create enumeration based on class syntax

Example

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3

The example defines the following:

  • Defines the enumerated type of Color.
  • The enumeration members of the enumeration type Color are defined: Color.red, Color.green, and Color.blue.
  • Assign a value to each enumeration member, such as the value of Color.red is 1. It should be noted that the value of an enumeration member can be specified as another type, and there is no mandatory requirement to be an integral type.

The enumeration member contains two attributes: name and value

>>>Color.red.name
red
>>>Color.red.value
1

Define string type value

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> from enum import Enum
>>> class Color(Enum):
...     red = 'r'
...     green = 'g'
...     blue = 'b'

Create enumeration based on Function API

The above example of creating enumeration based on class can be rewritten as

>>>from enum import Enum
>>>Color = Enum('Color','red green blue')
>>>list(Color)
[<Color.red:1>,<Color.green:2>,<Color.blue:3>]

The first parameter of the Enum function is the enumeration name. The second parameter is a list of enumerated members.

There are three ways for the enumeration member list represented by the second parameter:

  • It is represented by a string, and each member name is separated by a space. The value of the member is automatically incremented from 1.
  • Using tuples, the value of members is automatically incremented from 1.
  • Using a dictionary, the dictionary can specify the value of the enumeration member, where the key of the dictionary is the name of the enumeration member and the value is the value of the enumeration member.

Example of using dictionary declaration

>>>from enum import Enum
>>>Color = Enum('Color',{
    
    'red':1,'green':2,'blue':4})

Access enumeration member

There are three ways to access enumeration members:

  • Use dot (".") to quote
  • Use value to get the enumeration member corresponding to the value
  • Use enumeration member names

Access by value

>>>Color(1)
<Color.red:1>

Access by enumeration name

>>>Color['red']
<Color.red:1>

Traversing enum

Enumeration supports traversing its members

list traversal

>>>list(Color)
[<Color.red:1>,<Color.green:2>,<Color.blue:3>]

for traversal

>>>for color in Color:
...  print(color)

Comparison of enumerated types

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> Color.red is Color.red
True
>>> Color.red is Color.blue
False
>>> Color.red is not Color.blue
True

Note that the enumeration member is not an integral type, and size comparison cannot be done, such as

>>> Color.red < Color.blue
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Color() < Color()

Can only compare for equality

>>> Color.blue == Color.red
False
>>> Color.blue != Color.red
True
>>> Color.blue == Color.blue
True
>>> Color.blue == 2
False

Define the enumeration method

Since the enumeration type is also a class, it also supports defining methods for the enumeration type.

Example:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Mood(Enum):
  funky = 1
  happy = 3

  def describe(self):
    # self为枚举成员
    return self.name, self.value

  def __str__(self):
    return 'my custom str! {0}'.format(self.value)

  @classmethod
  def favorite_mood(cls):
    # cls为枚举类型
    return cls.happy

use:

>>> Mood.favorite_mood()
<Mood.happy: 3>
>>> Mood.happy.describe()
('happy', 3)
>>> str(Mood.funky)
'my custom str! 1'

Define subclasses of enum

The definition of subclasses of enumeration needs to meet: the parent enumeration does not define any enumeration members, and then subclasses are allowed.

>>> class MoreColor(Color):
...   pink = 17
...
TypeError: Cannot extend enumerations

This is because Mood has defined enumeration members and does not allow expansion.

Guess you like

Origin blog.csdn.net/qdPython/article/details/112844409