Python中枚举类型的详解(代码示例)


当前第2页 返回上一页

1

2

3

4

5

6

from enum import Enum, unique

@unique

class Color(Enum):

    red   = 1

    green = 2

    blue  = 1  # ValueError: duplicate values found in <enum 'Color'>: blue -> red

枚举取值

可以通过成员名来获取成员也可以通过成员值来获取成员:

1

2

3

print(Color['red'])  # Color.red  通过成员名来获取成员

 

print(Color(1))      # Color.red  通过成员值来获取成员

每个成员都有名称属性和值属性:

1

2

3

member = Color.red

print(member.name)   # red

print(member.value)  # 1

支持迭代的方式遍历成员,按定义的顺序,如果有值重复的成员,只获取重复的第一个成员:

1

2

for color in Color:

    print(color)

特殊属性 __members__ 是一个将名称映射到成员的有序字典,也可以通过它来完成遍历:

1

2

for color in Color.__members__.items():

    print(color)          # ('red', <Color.red: 1>)

枚举比较

枚举的成员可以通过 is 同一性比较或通过 == 等值比较:

1

2

3

4

5

Color.red is Color.red

Color.red is not Color.blue

 

Color.blue == Color.red

Color.blue != Color.red

枚举成员不能进行大小比较:

1

Color.red < Color.blue    # TypeError: unorderable types: Color() < Color()

扩展枚举 IntEnum

IntEnum 是 Enum 的扩展,不同类型的整数枚举也可以相互比较:

1

2

3

4

5

6

7

8

9

10

11

12

13

from enum import IntEnum

class Shape(IntEnum):

    circle = 1

    square = 2

 

class Request(IntEnum):

    post = 1

    get = 2

 

print(Shape.circle == 1)            # True

print(Shape.circle < 3)             # True

print(Shape.circle == Request.post) # True

print(Shape.circle >= Request.post) # True

总结

enum 模块功能很明确,用法也简单,其实现的方式也值得学习,有机会的话可以看看它的源码。

以上就是Python中枚举类型的详解(代码示例)的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

为什么人工智能要学Python

Python中的seed()方法怎么用

讲解Python 中删除文件的几种方法

如何用Python统计不同字符个数

Python中range()函数怎么用

什么是Python import语句?在Python中的import语句作用有哪些?

Python迭代器和for循环区别

Python两种错误类型的介绍

Python接口使用opencv的方法

怎么在Python安装pil

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...