热线电话:13121318867

登录
2019-03-28 阅读量: 518
python是通过什么模式访问枚举对象

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

1.按值: - 在此方法中,传递枚举成员的值。

2.按名称: - 在此方法中,传递枚举成员的名称。也可以使用“ name ”或“ value ”关键字访问单独的值或名称。

比较:枚举支持两种类型的比较

1.身份: - 使用关键字“ ”和“ 不是 ” 来检查这些身份

2.平等: - 也支持“ == ”和“ != ”类型的等式比较。

# Python code to demonstrate enumerations

# Access and comparison

# importing enum for enumerations

import enum

# creating enumerations using class

class Animal(enum.Enum):

dog = 1

cat = 2

lion = 3

# Accessing enum member using value

print ("The enum member associated with value 2 is : ",end="")

print (Animal(2))

# Accessing enum member using name

print ("The enum member associated with name lion is : ",end="")

print (Animal['lion'])

# Assigning enum member

mem = Animal.dog

# Displaying value

print ("The value associated with dog is : ",end="")

print (mem.value)

# Displaying name

print ("The name associated with dog is : ",end="")

print (mem.name)

# 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")

21.6081
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子