📅  最后修改于: 2023-12-03 15:18:55.114000             🧑  作者: Mango
In Python, an Enum (short for Enumeration) is a data type that contains a set of named values. It is used to define a group of constants that are readily identifiable by their names.
To create an Enum in Python, we use the enum
module. Here is an example of declaring an Enum:
from enum import Enum
class Fruit(Enum):
APPLE = 1
BANANA = 2
ORANGE = 3
In this example, we define an Enum called Fruit
. The constants within the Enum are defined using class attributes. Each constant is given a name, followed by its value.
Once an Enum is defined, we can use its constants in our code. Here is an example:
favorite_fruit = Fruit.APPLE
print(f"My favorite fruit is {favorite_fruit.name}.")
In this example, we create a variable favorite_fruit
and set it to the value Fruit.APPLE
. We then use the name
attribute to retrieve the name of the constant.
The enum
module provides several methods that can be used with Enum constants. Here are some examples:
fruit_value = 2
fruit = Fruit(fruit_value)
print(fruit.name)
In this example, we create a variable fruit_value
and set it to the value of 2
. We then use the Fruit
constructor to create an Enum constant with the value of 2
, and assign it to the variable fruit
. We then print the name of the constant.
for fruit in Fruit:
print(fruit.name)
In this example, we use a for
loop to iterate over all of the constants in the Fruit
Enum. We then print the name of each constant.
fruit_name = "APPLE"
fruit = Fruit[fruit_name]
print(fruit.value)
In this example, we create a variable fruit_name
and set it to "APPLE"
. We then use the bracket notation to access the APPLE
constant from the Fruit
Enum, and assign it to the variable fruit
. We then print the value of the constant.
Declaring an Enum in Python is a simple and effective way to group together related constants. Once an Enum is defined, its constants can be used in our code, and several methods are available to work with Enum constants.