In actual development, we cannot do without defining constants. When we need to define constants, one way is to use uppercase variables to define them with integers, such as months:
JAN = 1 FEB = 2 MAR = 3 ... NOV = 11 DEC = 12
Of course this is simple. Quick, the disadvantage is that the type is int, and it is still a variable.
Is there any good way?
At this time we define a class type, and each constant is the only instance in the class. It just so happens that Python provides the Enum class to implement this function as follows:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) # 遍历枚举类型 for name, member in Month.__members__.items(): print(name, '---------', member, '----------', member.value) # 直接引用一个常量 print('\n', Month.Jan)
The output result is as follows:
It can be seen that we can directly use Enum to define an enumeration Give a class. In the above code, we create an enumeration type Month about the month. What should be noted here is the construction parameters. The first parameter Month represents the class name of the enumeration class, and the second tuple parameter represents the enumeration. The value of the enumeration class; of course, the enumeration class traverses all its members through the __members__ method. One thing to note is that member.value is a constant of type int automatically assigned to members, starting from 1 by default. Moreover, the members of Enum are all singletons and cannot be instantiated or changed
Next Section