一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python中enum的使用代码方法

时间:2022-03-30 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python中enum的使用代码方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

前言:

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

在Python中没有内置的枚举方法,起初模仿实现枚举属性的方式是

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

使用成员:

Direction.EAST

Direction.SOUTH

检查成员:

>>> print("North的类型:", type(Direction.NORTH))
>>> print(isinstance(Direction.EAST, Direction))
North的类型: 
False

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

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

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

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

2.enum的定义/声明

from enum import Enum


class Directions(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

使用和类型检查:

>>> Directions.EAST

>>> Directions.SOUTH

>>> Directions.EAST.name
'EAST'
>>> Directions.EAST.value
2
>>> print("South的类型:", type(Directions.SOUTH))
South的类型: 
>>> print(isinstance(Directions.EAST, Directions))
True
>>> 

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

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

fetched_value = 2  # 获取值
if Directions(fetched_value) is Directions.NORTH:
    ...
elif Directions(fetched_value) is Directions.EAST:
    ...
else:
    ...

输入未定义的值时:

>>> Directions(5)
ValueError: 5 is not a valid Directions

3.遍历成员

>>> for name, value in Directions.__members__.items():
...     print(name, value)
...
NORTH Directions.NORTH
EAST Directions.EAST
SOUTH Directions.SOUTH
WEST Directions.WEST

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

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

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类属性的值定义为函数或方法

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__方法。

忽略大小写:

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"是未定义的属性值

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

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类的情况下,追加修改,这里借用一个说明示例,具体的场景使用案例可以看下面的场景举例

>>> # 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())
... 

[, , , ]
dict_items([('NORTH', ), ('EAST', ), ('SOUTH', ), ('WEST', )])
>>> # 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创建方法,这种在运行的过程中修改对象的方法也就是python的monkey patching。

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

在不修改某定义好的Enum类的代码块的情况下,下面示例中是Arithmethic类,可以认为是某源码库我们不想修改它,然后增加这个Enum类的属性,有两种方法:

1.enum.Enum对象的属性不可以直接被修改,但我们可以动态创建一个新的Enum类,以拓展原来的Enum对象

例如要为下面的Enum对象Arithmetic增加一个取模成员MOD="%",但是又不能修改Arithmetic类中的代码块:

# enum_test.py
from enum import Enum


class Arithmetic(Enum):
    ADD = "+"
    SUB = "-"
    MUL = "*"
    DIV = "/"

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

# 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.Enum类Arithmetic增加一个指数成员EXP="**",且不修改原来的Arithmetic类的代码块:

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

输出:

[, , , , ]

8

热门栏目