Home  >  Article  >  Backend Development  >  Enumeration types in Python

Enumeration types in Python

高洛峰
高洛峰Original
2016-11-22 17:13:541424browse

An enumeration type can be regarded as a label or a collection of constants, usually used to represent certain limited collections, such as days of the week, months, 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 simple enumerations In type implementation, 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 their normal use:

WEEKDAY['MON'] = WEEKDAY['FRI']print(WEEKDAY)
{'FRI': 5, 'TUS':
{'FRI': 5, 'TUS': 2, 'MON': 5, 'WEN': 3, 'THU': 4}

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

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 will lose the original intention of the enumeration type and degrade the label For meaningless variables:

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 supported libraries through pip install enum. enum provides three tools: Enum/IntEnum/unique, and the usage is very simple. You can define the enumeration type by inheriting Enum/IntEnum, where 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 values ​​of enumeration members to be non-repeatable:

from enum import Enum, IntEnum, uniquetry:    @unique
    class WEEKDAY(Enum):
        MON = 1
        TUS = 2
        WEN = 3
        THU = 4
        FRI = 1except ValueError as e:
    print(e)
duplicate values found in <enum &#39;WEEKDAY&#39;>: FRI -> MON
try:    class Color(IntEnum):
        RED   = 0
        GREEN = 1
        BLUE  = &#39;b&#39;except ValueError as e:
    print(e)
invalid literal for int() with base 10: &#39;b&#39;

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

class Color(Enum):
    R = 0
    G = 1
    B = 2
try:
    Color.R = 2except AttributeError as e:
    print(e)
Cannot reassign members.

Although it cannot be instantiated, the enumeration can be Members are assigned to variables:

red = Color(0)
green = Color(1)
blue = Color(2)
print(red, green, blue)
Color.R Color.G Color.B

You can also make comparisons and judgments:

print(red is Color.R)
print(red == Color.R)
print(red is blue)
print(green != Color.B)
print(red == 0) # 不等于任何非本枚举类的值
True
True
False
True
False

Last point, since the enumeration members themselves are also enumeration types, you can also find other members through the enumeration members:

print(red.B)
print(red.B.G.R)
Color.B
Color.R

But use this with caution Feature, because it may conflict with the name in the original namespace of the member:

print(red.name, &#39;:&#39;, red.value)

class Attr(Enum):
    name  = &#39;NAME&#39;
    value = &#39;VALUE&#39;
print(Attr.name.value, Attr.value.name)
R : 0
NAME value

Summary

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn