Home >Backend Development >Python Tutorial >what is enum python
The enumeration type can be regarded as a label or a collection of constants, usually used to represent certain limited collections, such as week, month, status, etc. There is no special enumeration type in Python's native types (Built-in types), but we can implement it through many methods, such as dictionaries, classes, etc.:
WEEKDAY = { 'MON': 1, 'TUS': 2, 'WEN': 3, 'THU': 4, 'FRI': 5 } class Color: RED = 0 GREEN = 1 BLUE = 2
The above two methods can be regarded as In the implementation of simple enumeration types, there is no problem if such enumeration variables are only used in the local scope, but the problem is that they are all mutable, which means they can be modified in other places and affect the implementation. Its normal use:
WEEKDAY['MON'] = WEEKDAY['FRI'] print(WEEKDAY) {'FRI': 5, 'TUS': 2, 'MON': 5, 'WEN': 3, 'THU': 4} 通过类定义的枚举甚至可以实例化,变得不伦不类: c = Color() print(c.RED) Color.RED = 2 print(c.RED) 0 2
Of course, you can also use immutable types (immutable), such as tuples, but this loses the original intention of the enumeration type and degrades the label into a meaningless variable:
COLOR = ('R', 'G', 'B') print(COLOR[0], COLOR[1], COLOR[2]) R G B
In order to provide a better solution, Python added the enum standard library in version 3.4 through PEP 435. Versions before 3.4 can also download compatible and supported libraries through pip install enum. enum provides three tools: Enum/IntEnum/unique, and their usage is very simple. You can define enumeration types by inheriting Enum/IntEnum. IntEnum limits the enumeration members to (or can be converted to) integer types, and the unique method can be used as The decorator restricts the value of the enumeration member to be non-repeatable:
from enum import Enum, IntEnum, unique try: @unique class WEEKDAY(Enum): MON = 1 TUS = 2 WEN = 3 THU = 4 FRI = 1 except ValueError as e: print(e) duplicate values found in : FRI -> MON try: class Color(IntEnum): RED = 0 GREEN = 1 BLUE = 'b' except ValueError as e: print(e) invalid literal for int() with base 10: 'b'
The above is the detailed content of what is enum python. For more information, please follow other related articles on the PHP Chinese website!