Learning python (thirteen)-enumeration class

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 at most 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, enumeration classes can be used to define them. 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.

E.g:

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

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). The 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.

It should be noted that the value of each member in the enumeration class cannot be modified outside the class. In addition, the enumeration class also provides a __members__ attribute, which is a dictionary containing all the members in the enumeration class. By traversing this attribute, you can also access each member in the enumeration class.

Each member of the Python enumeration class must ensure that the name is different from each other, but the value can be the same.

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113645800