Python?中enum的使用方法總結(jié)
前言:
枚舉(enumeration
)在許多編程語言中常被表示為一種基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu)使用,枚舉幫助組織一系列密切相關(guān)的成員到同一個群組機(jī)制下,一般各種離散的屬性都可以用枚舉的數(shù)據(jù)結(jié)構(gòu)定義,比如顏色、季節(jié)、國家、時間單位等
在Python中沒有內(nèi)置的枚舉方法,起初模仿實(shí)現(xiàn)枚舉屬性的方式是
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
標(biāo)準(zhǔn)庫enum實(shí)現(xiàn)了枚舉屬性的功能,接下來介紹enum的在實(shí)際工作生產(chǎn)中的用法
1.為什么要用enum,什么時候使用enum?
enum
規(guī)定了一個有限集合的屬性,限定只能使用集合內(nèi)的值,明確地聲明了哪些值是合法值,,如果輸入不合法的值會引發(fā)錯誤,只要是想要從一個限定集合取值使用的方式就可以使用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
的的類型,結(jié)果如期望的是Directions
。name
和value
是兩個有用的附加屬性。
實(shí)際工作中可能會這樣使用:
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的類中定義方法
可以用于將定義的值轉(zhuǎn)換為獲取需要的值
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類屬性的值定義為函數(shù)或方法
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.將函數(shù)方法用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.自定義異常處理
第一種,執(zhí)行SomeEnum
(“abc”)時想要引發(fā)自定義錯誤,其中"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
第二種:執(zhí)行SomeEnum.__getattr__
(“ABC”)時,想要引發(fā)自定義錯誤,其中"ABC"是未定義的屬性名稱,需要重寫一下EnumMeta中的__getattr__方法,然后指定實(shí)例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是屬性名稱,可以自定義固定傳入大寫(或小寫),對應(yīng)下面的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的進(jìn)階用法
Functional APIs
動態(tài)創(chuàng)建和修改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
注:這里沒有使用類直接聲明的方式來執(zhí)行枚舉(定義時如果不指定值默認(rèn)是從1開始的數(shù)字,也就相當(dāng)于NORTH = auto(),auto是enum中的方法),仍然可以在后面為這個動態(tài)創(chuàng)建的DirectionFunctional
創(chuàng)建方法,這種在運(yùn)行的過程中修改對象的方法也就是python
的monkey patching
。
Functional APIs的用處和使用場景舉例:
在不修改某定義好的Enum類的代碼塊的情況下,下面示例中是Arithmethic
類,可以認(rèn)為是某源碼庫我們不想修改它,然后增加這個Enum類的屬性,有兩種方法:
1.enum.Enum對象的屬性不可以直接被修改,但我們可以動態(tài)創(chuàng)建一個新的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
注意:動態(tài)創(chuàng)建Enum對象時,要指定原Enum類所在的module名稱: "Yourmodule",否則執(zhí)行時可能會因?yàn)檎也坏皆礋o法解析,qualname要指定類的位置:"Yourmodule.YourEnum",值用字符串類型
2.使用aenum.extend_enum可以動態(tài)修改enum.Enum對象
為enum.Enum
類Arithmetic
增加一個指數(shù)成員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
到此這篇關(guān)于Python 中enum的使用方法總結(jié)的文章就介紹到這了,更多相關(guān)Python enum使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中redis查看剩余過期時間及用正則通配符批量刪除key的方法
這篇文章主要介紹了python中redis查看剩余過期時間及用正則通配符批量刪除key的方法,需要的朋友可以參考下2018-07-07Python爬蟲實(shí)現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能案例
這篇文章主要介紹了Python爬蟲實(shí)現(xiàn)使用beautifulSoup4爬取名言網(wǎng)功能,結(jié)合實(shí)例形式分析了Python基于beautifulSoup4模塊爬取名言網(wǎng)并存入MySQL數(shù)據(jù)庫相關(guān)操作技巧,需要的朋友可以參考下2019-09-09淺談Keras參數(shù) input_shape、input_dim和input_length用法
這篇文章主要介紹了淺談Keras參數(shù) input_shape、input_dim和input_length用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06pycharm下配置pyqt5的教程(anaconda虛擬環(huán)境下+tensorflow)
這篇文章主要介紹了pycharm下配置pyqt5的教程(anaconda虛擬環(huán)境下+tensorflow),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03