Home > Backend Development > Python Tutorial > Enumeration types in Python

Enumeration types in Python

高洛峰
Release: 2016-11-22 17:13:54
Original
1489 people have browsed it

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
Copy after login

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':
Copy after login
{'FRI': 5, 'TUS': 2, 'MON': 5, 'WEN': 3, 'THU': 4}
Copy after login

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

c = Color()
print(c.RED)
Color.RED = 2
print(c.RED)
Copy after login
0
2
Copy after login

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])
Copy after login
R G B
Copy after login

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)
Copy after login
duplicate values found in <enum &#39;WEEKDAY&#39;>: FRI -> MON
Copy after login
try:    class Color(IntEnum):
        RED   = 0
        GREEN = 1
        BLUE  = &#39;b&#39;except ValueError as e:
    print(e)
Copy after login
invalid literal for int() with base 10: &#39;b&#39;
Copy after login

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
Copy after login
try:
    Color.R = 2except AttributeError as e:
    print(e)
Copy after login
Cannot reassign members.
Copy after login

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)
Copy after login
Color.R Color.G Color.B
Copy after login

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) # 不等于任何非本枚举类的值
Copy after login
True
True
False
True
False
Copy after login

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)
Copy after login
Color.B
Color.R
Copy after login

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)
Copy after login
R : 0
NAME value
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template