Python learning-use enumeration class

When we need to define constants, one way is to use uppercase variables to define integers, such as months:

JAN = 1
FEB = 2
MAR = 3
...
NOV = 11
DEC = 12

The advantage is simplicity, the disadvantage is that the type is int, and it is still a variable.
A better way is to define a class type for such enumerated types, and then each constant is a unique instance of class. Python provides the Enum class to achieve this function:

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

In this way, we have an enumeration class of type Month. You can directly use Month.Jan to reference a constant or enumerate all its members:

for name, member in Month.__members__.items():
	print(name, '=>', member, ',', member,value)

The value attribute is automatically assigned to the member int constants, counting from 1 by default.
If you need to control the enumeration types more precisely, you can derive a custom class from 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

The @unique decorator can help us check to ensure that there are no duplicate values.
There are several ways to access these enumerated types:

>>>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

It can be seen that the enumeration constant can be referenced by the member name, and the enumeration constant can be obtained directly according to the value.

Transform the student's gender attribute into an enumerated type to avoid the use of strings:

from enum import Enum, unique

class Gender(Enum):
	Male = 0
	Female = 1

class Student(object):
	def __init__(self, name, gender):
		self.name = name
		self.gender = gender


bart = Student('Bart', Gender.Male)
print(bart.gender) # 输出类,则显示类名.属性名
print(bart.gender.value) # 输出枚举类中的属性值
Gender.Male
0

summary

Enum can define a set of related constants in a class, and the class is immutable, and the members can be directly compared.

Guess you like

Origin blog.csdn.net/qq_44787943/article/details/112547737