溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中enum如何使用

發布時間:2022-03-30 16:45:34 來源:億速云 閱讀:228 作者:iii 欄目:開發技術

這篇文章主要介紹“Python中enum如何使用”,在日常操作中,相信很多人在Python中enum如何使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”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的類型: <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。namevalue是兩個有用的附加屬性。

實際工作中可能會這樣使用:

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創建方法,這種在運行的過程中修改對象的方法也就是pythonmonkey 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.EnumArithmetic增加一個指數成員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

到此,關于“Python中enum如何使用”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女