How to use the enum module to define enumeration types in Python 2.x
Introduction:
An enumeration is a data type that limits the value of a variable to a limited range. Use Enumeration types can make code clearer and more readable. In Python 2.x, we can use the enum module to define enumeration types. This article will introduce how to use the enum module to define and use enumeration types, and give corresponding code examples.
from enum import Enum
The following is a sample code that demonstrates how to define a Weekday enumeration type and give each enumeration value a corresponding name:
from enum import Enum class Weekday(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7
In this sample code, we A Weekday enumeration type is defined, which contains seven enumeration values, corresponding to Monday to Sunday.
The following is a sample code that shows how to use the Weekday enumeration type:
print(Weekday.MONDAY) # 输出:Weekday.MONDAY print(Weekday.SUNDAY) # 输出:Weekday.SUNDAY
In this sample code, we print the two enumeration values in the Weekday enumeration type .
The following is a sample code that shows how to compare two enumeration values in the Weekday enumeration type:
if Weekday.MONDAY == Weekday.MONDAY: print("Monday is equal to Monday") # 输出:Monday is equal to Monday
In this sample code, we compare two Weekday The enumeration value in the enumeration type is subject to conditional judgment based on the comparison result.
Summary:
This article introduces how to use the enum module to define enumeration types in Python 2.x, and gives corresponding code examples. By using enumeration types we can make the code clearer and readable. In actual development, when you need to limit the value range of a variable, using enumeration types will be very helpful.
The above is the detailed content of How to use the enum module to define enumeration types in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!