Python中的枚举enum

Python中的枚举是使用名为“enum”的模块实现的。枚举是使用类创建的。枚举具有与之关联的名称和值。

枚举的属性:

  • 枚举可以显示为string或repr。
  • 可以使用type()检查枚举的类型。
  • “name”关键字用于显示枚举成员的名称。

1. Python中的Enum类

from enum import Enum

class Season(Enum):
	SPRING = 1
	SUMMER = 2
	AUTUMN = 3
	WINTER = 4

# printing enum member as string
print(Season.SPRING)

# printing name of enum member using "name" keyword
print(Season.SPRING.name)

# printing value of enum member using "value" keyword
print(Season.SPRING.value)

# printing the type of enum member using type()
print(type(Season.SPRING))

# printing enum member as repr
print(repr(Season.SPRING))

# printing all enum member using "list" keyword
print(list(Season))

输出

Season.SPRING
SPRING
1
<enum 'Season'>
<Season.SPRING: 1>
[<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]

2. 访问模式

可以通过两种方式访问枚举成员:

  • 通过值:在此方法中,传递枚举成员的值。
  • 通过名称:在此方法中,传递枚举成员的名称。

也可以使用“name”或“value”关键字访问单独的值或名称。

from enum import Enum

class Season(Enum):
	SPRING = 1
	SUMMER = 2
	AUTUMN = 3
	WINTER = 4

# Accessing enum member using value
print("The enum member associated with value 2 is : ", Season(2).name)

# Accessing enum member using name
print("The enum member associated with name AUTUMN is : ", Season['AUTUMN'].value)

输出

The enum member associated with value 2 is :  SUMMER
The enum member associated with name AUTUMN is :  3

3. 枚举是可迭代的,可以使用循环来迭代它们

在这个例子中,我们将使用for循环来打印Enum类的所有成员。

from enum import Enum

class Season(Enum):
	SPRING = 1
	SUMMER = 2
	AUTUMN = 3
	WINTER = 4

for season in (Season):
	print(season.value,"-",season)

输出

1 - Season.SPRING
2 - Season.SUMMER
3 - Season.AUTUMN
4 - Season.WINTER

4. 枚举支持哈希

import enum

# creating enumerations using class
class Animal(enum.Enum):
	dog = 1
	cat = 2
	lion = 3

# Hashing enum member as dictionary
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'

# checking if enum values are hashed successfully
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
	print("Enum is hashed")
else:
	print("Enum is not hashed")

输出

Enum is hashed

5. 枚举支持两种类型的比较

  • is:使用关键字“is”和“is not”检查这些。
  • 等于:“==”和“的相等比较!=”类型也支持。
import enum

# creating enumerations using class
class Animal(enum.Enum):
	dog = 1
	cat = 2
	lion = 3

# Comparison using "is"
if Animal.dog is Animal.cat:
	print("Dog and cat are same animals")
else:
	print("Dog and cat are different animals")

# Comparison using "!="
if Animal.lion != Animal.cat:
	print("Lions and cat are different")
else:
	print("Lions and cat are same")

输出

Dog and cat are different animals
Lions and cat are different
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值