Python enumeration class definition and use

For some classes with special meanings, the number of instantiated objects is often fixed. For example, if a class is used to represent the month, there are up to 12 instance objects of this class; for another example, if a class is used to represent the season, then the instance of this class There are a maximum of 4 objects.

For this special class, the Enum enumeration class is newly added in Python 3.4. In other words, for these classes with a fixed number of instantiated objects, they can be defined by enumeration classes.

For example, the following program demonstrates how to define an enumeration class:

from enum import Enum
class Color(Enum):
    # 为序列值指定value值
    red = 1
    green = 2
    blue = 3

If you want to define a class as an enumeration class, you only need to make it inherit from the Enum class in the enum module. For example, in the above program, the Color class inherits from the Enum class, which proves that this is an enumeration class.

In the Color enumeration class, red, green, and blue are all members of this class (can be understood as class variables). Note that each member of the enumeration class consists of two parts, namely name and value, where the name attribute value is the variable name of the enumeration value (such as red), and value represents the serial number of the enumeration value (the serial number is usually from 1 start).

Unlike the usage of ordinary classes, enumeration classes cannot be used to instantiate objects, but this does not prevent us from accessing members of enumeration classes. There are many ways to access the members of the enumeration class. For example, take the Color enumeration class as an example, and add the following code to it:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#调用枚举成员的 3 种方式
print(Color.red)
print(Color['red'])
print(Color(1))
#调取枚举成员中的 value 和 name
print(Color.red.value)
print(Color.red.name)
#遍历枚举类中所有成员的 2 种方式
for color in Color:
    print(color)

The output of the program is:

Color.red
Color.red
Color.red
1
red
Color.red
Color.green
Color.blue

Enumeration members cannot be compared, but you can use == or is to compare whether they are equal, for example:

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

输出结果为:

Flase
Flase

It should be noted that the value of each member in the enumeration class cannot be modified outside the class. In other words, the following syntax is wrong:

Color.red = 4

In addition, the enumeration class also provides a __ members __ attribute, which is a dictionary containing all the members of the enumeration class. By traversing this attribute, you can also access each member of the enumeration class. E.g:

for name,member in Color.__members__.items():
    print(name,"->",member)

The output is:

red -> Color.red
green -> Color.green
blue -> Color.blue

It is worth mentioning that each member of the Python enumeration class must ensure that the name is different from each other, but the value can be the same. For example:

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

class Color(Enum):
    # 为序列值指定value值
    red = 1
    green = 1
    blue = 3
print(Color['green'])

输出结果为:

Color.red

As you can see, red and green in the Color enumeration class have the same value (both are 1). Python allows this to happen. It treats green as an alias for red, so when accessing the green member, the final output Is red.

In the actual programming process, if you want to avoid this situation, you can use the @unique decorator, so that when a member with the same value appears in the enumeration class, the program will report a ValueError error. E.g:

#引入 unique
from enum import Enum,unique
#添加 unique 装饰器
@unique
class Color(Enum):
    # 为序列值指定value值
    red = 1
    green = 1
    blue = 3
print(Color['green'])

Running the program will report an error:

Traceback (most recent call last):
  File "D:\python3.6\demo.py", line 3, in <module>
    class Color(Enum):
  File "D:\python3.6\lib\enum.py", line 834, in unique
    (enumeration, alias_details))
ValueError: duplicate values found in <enum 'Color'>: green -> red

In addition to creating an enumeration class by inheriting the Enum class method, you can also use the Enum() function to create an enumeration class. E.g:

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

#调用枚举成员的 3 种方式
print(Color.red)
print(Color['red'])
print(Color(1))
#调取枚举成员中的 value 和 name
print(Color.red.value)
print(Color.red.name)
#遍历枚举类中所有成员的 2 种方式
for color in Color:
    print(color)

Enum() function accepts 2 parameters, the first is used to specify the class name of the enumeration class, and the second parameter is used to specify multiple members in the enumeration class.

As shown above, with only one line of code, an enumeration class identical to the previous Color class is created. Run the program, the output result is:

Color.red
Color.red
Color.red
1
red
Color.red
Color.green
Color.blue

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/108681726