日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python enum的使用总结

發布時間:2024/7/5 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python enum的使用总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python enum的使用總結

枚舉(enumeration)在許多編程語言中常被表示為一種基礎的數據結構使用,枚舉幫助組織一系列密切相關的成員到同一個群組機制下,一般各種離散的屬性都可以用枚舉的數據結構定義,比如顏色、季節、國家、時間單位等
在Python中沒有內置的枚舉方法,起初模仿實現枚舉屬性的方式是

class Directions:NORTH = 1EAST = 2SOUTH = 3WEST = 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的在實際工作生產中的用法

為什么要用enum,什么時候使用enum?

enum規定了一個有限集合的屬性,限定只能使用集合內的值,明確地聲明了哪些值是合法值,,如果輸入不合法的值會引發錯誤,只要是想要從一個限定集合取值使用的方式就可以使用enum來組織值。

enum的定義/聲明

from enum import Enumclass Directions(Enum):NORTH = 1EAST = 2SOUTH = 3WEST = 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

遍歷成員

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

在繼承Enum的類中定義方法

可以用于將定義的值轉換為獲取需要的值

from enum import Enumclass Directions(Enum):NORTH = 1EAST = 2SOUTH = 3WEST = 4def angle(self):right_angle = 90.0return right_angle * (self.value - 1)@staticmethoddef 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

將Enum類屬性的值定義為函數或方法

from enum import Enum from functools import partialdef plus_90(value):return Directions(value).angle + 90class Directions(Enum):NORTH = 1EAST = 2SOUTH = 3WEST = 4PLUS_90 = partial(plus_90)def __call__(self, *args, **kwargs):return self.value(*args, **kwargs)@propertydef angle(self):right_angle = 90.0return 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"@classmethoddef _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

自定義異常處理

第一種,執行SomeEnum(“abc”)時想要引發自定義錯誤,其中"abc"是未定義的屬性值

class TimeUnit(Enum):MONTH = "MONTH"WEEK = "WEEK"DAY = "DAY"HOUR = "HOUR"MINUTE = "MINUTE"@classmethoddef _missing_(cls, value: str):raise Exception("Customized exception")print(TimeUnit("MONTH")) TimeUnit("abc")

輸出

TimeUnit.MONTHValueError: '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 partialclass SomeEnumMeta(EnumMeta):def __getattr__(cls, name: str):value = cls.__members__.get(name.upper()) # (這里name是屬性名稱,可以自定義固定傳入大寫(或小寫),對應下面的A1是大寫)if not value:raise Exception("Customized exception")return valueclass 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.A1123... Exception: Customized exception

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 Enumclass Arithmetic(Enum):ADD = "+"SUB = "-"MUL = "*"DIV = "/"

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

# functional_api_test.py from enum import EnumDynamicEnum = 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 Arithmeticextend_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://betterprogramming.pub/take-advantage-of-the-enum-class-to-implement-enumerations-in-python-1b65b530e1d
https://docs.python.org/3/library/enum.html
https://stackoverflow.com/questions/28126314/adding-members-to-python-enums

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Python enum的使用总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。