Python物件導向高階程式設計 使用列舉類

2021-08-18 20:29:37 字數 1921 閱讀 8377

當我們需要定義常量時,乙個辦法是用大寫變數通過整數來定義,例如

月份:一月 jan = 1

二月 feb=2

三月 mar=3

四月 apr=4

五月 may=5

六月 jun=6

七月 jul=7

八月 aug=8

九月 sep=9 

十月 oct=10

十一月 nov=11

十二月 dec=12

好處是簡單,缺點是型別是int,並且仍然是變數。

更好的方法是為這樣的列舉型別定義乙個class型別,然後,每個常量都是class的乙個唯一例項。python提供了enum類來實現這個功能:

from enum import enum

month = enum('month', ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul','aug', 'sep', 'oct', 'nov', 'dec'))

這樣我們就獲得了month型別的列舉類,可以直接使用month.jan來引用乙個常量,或者列舉它的所有成員:

for name, member in month.__members__.items():

print(name, '=>', member, ',', member.value)

value屬性則是自動賦值給成員的int常量,預設從1開始計數。

如果需要更精準地控制列舉型別,可以從enum派生出自定義類:

from enum import enum, unique

@unique

class weekday(enum):

sun = 0 # sun 的 value 被設定為 0

mon = 1

tue = 2

wed = 3

thu = 4

fri = 5

sat = 6

@unique裝飾器可以幫助我們檢查保證沒有重複值。

訪問這些列舉型別可以有若干種方法:

>>> day1 = weekday.mon

>>> print(day1)

weekday.mon

>>> print(weekday.tue)

weekday.tue

>>> print(weekday['tue'])

weekday.tue

>>> print(weekday.tue.value)

2>>> print(day1 == weekday.mon)

true

>>> print(day1 == weekday.tue)

false

>>> print(weekday(1))

weekday.mon

>>> print(day1 == weekday(1))

true

>>> weekday(7)

traceback (most recent call last):

...valueerror: 7 is not a valid weekday

>>> for name, member in weekday.__members__.items():

...     print(name, '=>', member)

...sun => weekday.sun

mon => weekday.mon

tue => weekday.tue

wed => weekday.wed

thu => weekday.thu

fri => weekday.fri

sat => weekday.sat

可見,既可以用成員名稱引用列舉常量,又可以直接根據value的值獲得列舉常量。

python 物件導向高階程式設計

python 裝飾器 property使用 classscreen property defwidth self returnself.width pass width.setter defwidth self,value self.width value property defheight se...

python物件導向高階程式設計

1.繫結方法 給所有例項都繫結方法,可以給class繫結方法 def set score self,score self.score score student.set score set score 給class繫結方法後,所有例項均可呼叫。但是,如果我們想要限制例項的屬性怎麼辦?比如,只允許對s...

物件導向高階程式設計

相同class的各物件互為友元 class complex int func const complex param private double re,im string inline string string const char cstr 0 else inline string strin...