網站首頁 編程語言 正文
前言:
枚舉(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的類型: <class 'int'> 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.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
的的類型,結果如期望的是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()) ...? <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
創建方法,這種在運行的過程中修改對象的方法也就是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"))
輸出:
<enum 'Arithmetic'> [<Arithmetic.ADD: '+'>, <Arithmetic.SUB: '-'>, <Arithmetic.MUL: '*'>, <Arithmetic.DIV: '/'>, <Arithmetic.EXP: '**'>]
8
原文鏈接:https://blog.csdn.net/Moelimoe/article/details/121435602
相關推薦
- 2023-02-06 shell腳本實戰之部署nginx腳本實例_nginx
- 2022-05-01 Python類的定義和使用詳情_python
- 2022-01-16 span設置寬高無效
- 2022-04-16 Redis命令處理過程源碼解析_Redis
- 2022-08-24 使用chrome控制臺作為.Net的日志查看器_實用技巧
- 2022-04-05 expected a string (for built-in components) or a c
- 2022-02-10 C語言之初識指針_C 語言
- 2022-08-05 基于python詳解PyScript到底是什么_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支