Python 枚举

Python 枚举

Enum是Python中的一个类,用于创建枚举。枚举是一组与特定值绑定的符号名称(成员)。枚举的成员可以使用这些符号名称进行比较,并且可以对枚举本身进行迭代。枚举具有以下特点。

  • 枚举是一个对象的可评估字符串表示,也被称为repr()。

  • 使用’name’关键字显示枚举的名称。

  • 使用type()可以检查枚举的类型。

示例1

import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
   Tue = 3
# print the enum member as a string
print ("The enum member as a string is : ",end="")
print (Days.Mon)

# print the enum member as a repr
print ("he enum member as a repr is : ",end="")
print (repr(Days.Sun))

# Check type of enum member
print ("The type of enum member is : ",end ="")
print (type(Days.Mon))

# print name of enum member
print ("The name of enum member is : ",end ="")
print (Days.Tue.name)

输出

运行上述代码给我们以下结果 –

The enum member as a string is : Days.Mon
he enum member as a repr is :
The type of enum member is :
The name of enum member is : Tue

将枚举作为可迭代对象打印

我们可以将枚举作为可迭代列表打印出来。在下面的代码中,我们使用一个for循环来打印所有枚举成员。

示例2

import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
   Tue = 3
# printing all enum members using loop
print ("The enum members are : ")
for weekday in (Days):
print(weekday)

输出

运行上述代码会给我们以下结果 –

The enum members are :
Days.Sun
Days.Mon
Days.Tue

哈希枚举

枚举中的成员是可哈希的,因此它们可以用于字典和集合。在下面的示例中,我们可以看到哈希的应用,并检查哈希是否成功。

示例

import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
# Hashing to create a dictionary
Daytype = {}
Daytype[Days.Sun] = 'Sun God'
Daytype[Days.Mon] = 'Moon God'

# Checkign if the hashing is successful
print(Daytype =={Days.Sun:'Sun God',Days.Mon:'Moon God'})

输出

运行以上代码会得到以下结果:

True

访问枚举

我们可以通过使用成员项的名称或值来访问枚举成员。在下面的示例中,我们首先根据名称访问值,其中我们使用枚举的名称作为索引。

示例

import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
print('enum member accessed by name: ')
print (Days['Mon'])
print('enum member accessed by Value: ')
print (Days(1))

输出

运行以上代码会得到以下结果−

enum member accessed by name:
Days.Mon
enum member accessed by Value:
Days.Sun

比较枚举类型

比较枚举类型是一个直接的过程,我们使用 比较运算符 。

示例

import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
   Tue = 1
if Days.Sun == Days.Tue:
   print('Match')
if Days.Mon != Days.Tue:
print('No Match')

输出

运行以上代码会给我们带来下面的结果 –

Match
No Match

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程