Who said that Python has no enumerated types, stop talking about it, take a good look!

An enumeration type can be seen as a label or a collection of a series of constants, usually used to represent some specific limited collection, such as week, month, status, etc.

There is no special enumeration type in Python's built-in types, but we can implement it in many ways, such as dictionaries, classes, etc.:

MiracleLove = {'MON': '林志玲', 'TUS': '陈意涵', 'WEN': '张柏芝', 'THU': '辛芷蕾', 'FRI': '周冬雨'}

class MiracleLove:
   MON = '林志玲'
   TUS = '陈意涵'
   WEN = '张柏芝'
   THU = '辛芷蕾'
   FRI = '周冬雨'

The above two methods can be regarded as the realization of simple enumeration types.

There is no problem if such enumeration variables are used only in a local scope.

But the problem is that they are all mutable, which means they can be modified elsewhere to affect their normal use:

MiracleLove['MON'] = MiracleLove['FRI']
print(MiracleLove)

Enumerations defined by classes can even be instantiated and become nondescript:

ml = MiracleLove()
print(ml.MON)

MiracleLove.MON = 2
print(ml.MON)

Of course, immutable types (immutable) can also be used, such as tuples, but this loses the original meaning of enumeration types and degenerates tags into meaningless variables:

MiracleLove = ('R', 'G', 'B')
print(MiracleLove[0], MiracleLove[1], MiracleLove[2])

In order to provide a better solution, Python added the enum standard library in version 3.4 through PEP 435. For versions before 3.4, you can also download compatible support libraries through pip install enum.

Enum provides Enum/IntEnum/unique three tools, the usage is also very simple, you can define enumeration types by inheriting Enum/IntEnum, where IntEnum restricts enumeration members must be (or can be converted to) integer types, and the unique method can be used as The modifier restricts the value of enumeration members to not repeating:

from enum import Enum, IntEnum, unique

try:
   @unique
   class MiracleLove(Enum):
       MON = '林志玲'
       TUS = '陈意涵'
       WEN = '张柏芝'
       THU = '辛芷蕾'
       FRI = '周冬雨'
except ValueError as e:
   print(e)
   
# duplicate values found in <enum 'MiracleLove'>: FRI -> MON

I have a circle of learning and communication. Although the number of people is not very large, everyone who learns python comes to learn and communicate. What problems
are encountered? Discuss with each other and exchange academic issues with each other. Learn to communicate with the penguin group: 745895701

try:
   class MiracleLove(IntEnum):
       MON = 1
       TUS = 2
       WEN = 3
       THU = 4
       FRI = '周冬雨'
except ValueError as e:
   print(e)

# invalid literal for int() with base 10: '周冬雨'

What's more interesting is that the members of Enum are all singletons, and cannot be instantiated or changed:

class MiracleLove(Enum):
   MON = '林志玲'
   TUS = '陈意涵'
   WEN = '张柏芝'
   THU = '辛芷蕾'
   FRI = '周冬雨'

try:
   MiracleLove.MON = 2
except AttributeError as e:
   print(e)

# Cannot reassign members.

Although it is not instantiable, you can assign enumeration members to variables:

mon = MiracleLove(0)
tus = MiracleLove(1)
wen = MiracleLove(2)
print(mon, tus, wen)

# MiracleLove.MON 
# MiracleLove.TUS 
# MiracleLove.WEN

You can also make comparison judgments:

print(mon is MiracleLove.MON)
print(mon == MiracleLove.MON)
print(mon is tus)
print(wen != MiracleLove.TUS)
print(mon == 0) # 不等于任何非本枚举类的值

# True
# True
# False
# True
# False

Finally, because enumeration members themselves are also enumeration types, other members can also be found through enumeration members:

print(mon.TUS)
print(mon.TUS.WEN.MON)

# MiracleLove.TUS
# MiracleLove.MON

But use this feature with caution, because it may conflict with the name in the member's original namespace:

print(mon.name, ':', mon.value)

class Attr(Enum):
   name  = 'NAME'
   value = 'VALUE'

print(Attr.name.value, Attr.value.name)

# R : 0
# NAME value

to sum up:

The usage of enum module is very simple and its function is very clear, but its implementation is very worth learning. If you want to learn more about the black magic of Class and Metaclass in Python, and don't know how to get started, then you might as well read the source code of enum.

Guess you like

Origin blog.csdn.net/Python_xiaobang/article/details/112800451
Recommended