脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 中enum的使用方法总结

Python 中enum的使用方法总结

2022-11-17 11:53Moelimoe Python

这篇文章主要介绍了Python 中enum的使用方法总结,枚举在许多编程语言中常被表示为一种基础的数据结构使用,下文更多详细内容需要的小伙伴可以参考一下

前言:

枚举(enumeration)在许多编程语言中常被表示为一种基础的数据结构使用,枚举帮助组织一系列密切相关的成员到同一个群组机制下,一般各种离散的属性都可以用枚举的数据结构定义,比如颜色、季节、国家、时间单位等
在Python中没有内置的枚举方法,起初模仿实现枚举属性的方式是

?
1
2
3
4
5
class Directions:
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

使用成员:

Direction.EAST 
Direction.SOUTH 

检查成员:

?
1
2
3
4
>>> print("North的类型:", type(Direction.NORTH))
>>> print(isinstance(Direction.EAST, Direction))
North的类型: <class 'int'>
False

成员NORTH的类型是int,而不是Direction,这个做法只是简单地将属性定义到类中

Python标准库enum实现了枚举属性的功能,接下来介绍enum的在实际工作生产中的用法

1.为什么要用enum,什么时候使用enum?

enum规定了一个有限集合的属性,限定只能使用集合内的值,明确地声明了哪些值是合法值,,如果输入不合法的值会引发错误,只要是想要从一个限定集合取值使用的方式就可以使用enum来组织值。

2.enum的定义/声明

?
1
2
3
4
5
6
7
8
from enum import Enum
 
 
class Directions(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

使用和类型检查:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> Directions.EAST
<Directions.EAST: 2>
>>> Directions.SOUTH
<Directions.SOUTH: 3>
>>> Directions.EAST.name
'EAST'
>>> Directions.EAST.value
2
>>> print("South的类型:", type(Directions.SOUTH))
South的类型: <enum 'Directions'>
>>> print(isinstance(Directions.EAST, Directions))
True
>>> 

检查示例South的的类型,结果如期望的是Directionsnamevalue是两个有用的附加属性。

实际工作中可能会这样使用:

?
1
2
3
4
5
6
7
fetched_value = 2  # 获取值
if Directions(fetched_value) is Directions.NORTH:
    ...
elif Directions(fetched_value) is Directions.EAST:
    ...
else:
    ...

输入未定义的值时:

?
1
2
>>> Directions(5)
ValueError: 5 is not a valid Directions

3.遍历成员

?
1
2
3
4
5
6
7
>>> for name, value in Directions.__members__.items():
...     print(name, value)
...
NORTH Directions.NORTH
EAST Directions.EAST
SOUTH Directions.SOUTH
WEST Directions.WEST

4.继承Enum的类中定义方法

可以用于将定义的值转换为获取需要的值

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from enum import Enum
 
 
class Directions(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4
 
    def angle(self):
        right_angle = 90.0
        return right_angle * (self.value - 1)
 
    @staticmethod
    def angle_interval(direction0, direction1):
        return abs(direction0.angle() - direction1.angle())
 
>>> east = Directions.EAST
>>> print("SOUTH Angle:", east.angle())
SOUTH Angle: 90.0
>>> west = Directions.WEST
>>> print("Angle Interval:", Directions.angle_interval(east, west))
Angle Interval: 180.0

5.将Enum类属性的值定义为函数或方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from enum import Enum
from functools import partial
 
 
def plus_90(value):
    return Directions(value).angle + 90
 
 
class Directions(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4
    PLUS_90 = partial(plus_90)
 
    def __call__(self, *args, **kwargs):
        return self.value(*args, **kwargs)
 
    @property
    def angle(self):
        right_angle = 90.0
        return right_angle * (self.value - 1)
 
 
print(Directions.NORTH.angle)
print(Directions.EAST.angle)
south = Directions(3)
print("SOUTH angle:", south.angle)
print("SOUTH angle plus 90: ", Directions.PLUS_90(south.value))

输出:

0.0
90.0
SOUTH angle: 180.0
SOUTH angle plus 90:  270.0

key: 1.将函数方法用partial包起来;2.定义__call__方法。

忽略大小写:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TimeUnit(Enum):
    MONTH = "MONTH"
    WEEK = "WEEK"
    DAY = "DAY"
    HOUR = "HOUR"
    MINUTE = "MINUTE"
    
    @classmethod
    def _missing_(cls, value: str):
        for member in cls:
            if member.value == value.upper():
                return member
print(TimeUnit("MONTH"))
print(TimeUnit("Month"))

继承父类Enum_missing_方法,在值的比较时将case改为一致即可

输出:

TimeUnit.MONTH
TimeUnit.MONTH

6.自定义异常处理

第一种,执行SomeEnum(“abc”)时想要引发自定义错误,其中"abc"是未定义的属性值

?
1
2
3
4
5
6
7
8
9
10
11
12
13
class TimeUnit(Enum):
    MONTH = "MONTH"
    WEEK = "WEEK"
    DAY = "DAY"
    HOUR = "HOUR"
    MINUTE = "MINUTE"
 
    @classmethod
    def _missing_(cls, value: str):
        raise Exception("Customized exception")
 
print(TimeUnit("MONTH"))
TimeUnit("abc")

输出:

TimeUnit.MONTH

ValueError: 'abc' is not a valid TimeUnit
...
Exception: Customized exception

第二种:执行SomeEnum.__getattr__(“ABC”)时,想要引发自定义错误,其中"ABC"是未定义的属性名称,需要重写一下EnumMeta中的__getattr__方法,然后指定实例Enum对象的的metaclass

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from enum import Enum, EnumMeta
from functools import partial
 
 
class SomeEnumMeta(EnumMeta):
    def __getattr__(cls, name: str):
        value = cls.__members__.get(name.upper())   # (这里name是属性名称,可以自定义固定传入大写(或小写),对应下面的A1是大写)
        if not value:
            raise Exception("Customized exception")
        return value
 
 
class SomeEnum1(Enum, metaclass=SomeEnumMeta):
    A1 = "123"
 
 
class SomeEnum2(Enum, metaclass=SomeEnumMeta):
    A1 = partial(lambda x: x)
 
    def __call__(self, *args, **kwargs):
        return self.value(*args, **kwargs)
 
 
print(SomeEnum1.__getattr__("A1"))
print(SomeEnum2.__getattr__("a1")("123"))
print(SomeEnum2.__getattr__("B")("123"))

输出:

SomeEnum1.A1

123

...
Exception: Customized exception

7.enum的进阶用法

Functional APIs

动态创建和修改Enum对象,可以在不修改原定义好的Enum类的情况下,追加修改,这里借用一个说明示例,具体的场景使用案例可以看下面的场景举例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> # Create an Enum class using the functional API
... DirectionFunctional = Enum("DirectionFunctional", "NORTH EAST SOUTH WEST", module=__name__)
... # Check what the Enum class is
... print(DirectionFunctional)
... # Check the items
... print(list(DirectionFunctional))
... print(DirectionFunctional.__members__.items())
... 
<enum 'DirectionFunctional'>
[<DirectionFunctional.NORTH: 1>, <DirectionFunctional.EAST: 2>, <DirectionFunctional.SOUTH: 3>, <DirectionFunctional.WEST: 4>]
dict_items([('NORTH', <DirectionFunctional.NORTH: 1>), ('EAST', <DirectionFunctional.EAST: 2>), ('SOUTH', <DirectionFunctional.SOUTH: 3>), ('WEST', <DirectionFunctional.WEST: 4>)])
>>> # Create a function and patch it to the DirectionFunctional class
... def angle(DirectionFunctional):
...     right_angle = 90.0
...     return right_angle * (DirectionFunctional.value - 1)
... 
... 
... DirectionFunctional.angle = angle
... 
... # Create a member and access its angle
... south = DirectionFunctional.SOUTH
... print("South Angle:", south.angle())
... 
South Angle: 180.0

注:这里没有使用类直接声明的方式来执行枚举(定义时如果不指定值默认是从1开始的数字,也就相当于NORTH = auto(),auto是enum中的方法),仍然可以在后面为这个动态创建的DirectionFunctional创建方法,这种在运行的过程中修改对象的方法也就是pythonmonkey patching

Functional APIs的用处和使用场景举例:

在不修改某定义好的Enum类的代码块的情况下,下面示例中是Arithmethic类,可以认为是某源码库我们不想修改它,然后增加这个Enum类的属性,有两种方法:
1.enum.Enum对象的属性不可以直接被修改,但我们可以动态创建一个新的Enum类,以拓展原来的Enum对象
例如要为下面的Enum对象Arithmetic增加一个取模成员MOD="%",但是又不能修改Arithmetic类中的代码块:

?
1
2
3
4
5
6
7
8
9
# enum_test.py
from enum import Enum
 
 
class Arithmetic(Enum):
    ADD = "+"
    SUB = "-"
    MUL = "*"
    DIV = "/"

就可以使用enum的Functional APIs方法:

?
1
2
3
4
5
6
7
8
# functional_api_test.py
from enum import Enum
 
DynamicEnum = Enum("Arithmetic", {"MOD": "%"}, module="enum_test", qualname="enum_test.Arithmetic")
 
print(DynamicEnum.MOD)
 
print(eval(f"5 {DynamicEnum.MOD.value} 3"))

输出:

Arithmetic.MOD

2

注意:动态创建Enum对象时,要指定原Enum类所在的module名称: "Yourmodule",否则执行时可能会因为找不到源无法解析,qualname要指定类的位置:"Yourmodule.YourEnum",值用字符串类型

2.使用aenum.extend_enum可以动态修改enum.Enum对象

enum.EnumArithmetic增加一个指数成员EXP="**",且不修改原来的Arithmetic类的代码块:

?
1
2
3
4
5
6
7
8
# functional_api_test.py
from aenum import extend_enum
from enum_test import Arithmetic
 
 
extend_enum(Arithmetic, "EXP", "**")
print(Arithmetic, list(Arithmetic))
print(eval(f"2 {Arithmetic.EXP.value} 3"))

输出:

<enum 'Arithmetic'> [<Arithmetic.ADD: '+'>, <Arithmetic.SUB: '-'>, <Arithmetic.MUL: '*'>, <Arithmetic.DIV: '/'>, <Arithmetic.EXP: '**'>]
8

到此这篇关于Python 中enum的使用方法总结的文章就介绍到这了,更多相关Python enum使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Moelimoe/article/details/121435602

延伸 · 阅读

精彩推荐