search
HomeBackend DevelopmentPython TutorialDetailed explanation of enumeration types in Python (code examples)

This article brings you a detailed explanation (code example) of enumeration types in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Python’s native types do not include enumeration types. To provide a better solution, Python added the enum standard library in version 3.4 via PEP 435.

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. What do we do when there is no specifically provided enumeration type? Generally, it is implemented through a dictionary or class:

Color = {
    'RED'  : 1,
    'GREEN': 2,
    'BLUE' : 3,
}
class Color:
    RED   = 1
    GREEN = 2
    BLUE  = 3

This way of implementing enumeration is of course no problem if it is used carefully. After all, it is a compromise. s solution. The danger is that it can be modified.

Using Enum

A better way is to use the Enum type provided by the standard library. The official library is trustworthy. Versions before 3.4 can also download supported libraries through pip install enum. Simple example:

from enum import Enum
class Color(Enum):
    red = 1
    green = 2
    blue = 3

Enumeration members have values ​​(repeatable by default), and enumeration members have friendly string representations:

>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<color.red:>
>>> type(Color.red)
<enum>
>>> isinstance(Color.green, Color)
True</enum></color.red:>

Enumeration types are not instantiable and cannot be changed.

Define enumeration

When defining an enumeration, the member name is not allowed to be repeated

class Color(Enum):
    red = 1
    green = 2
    red = 3    # TypeError: Attempted to reuse key: 'red'

The member value is allowed to be the same, the second member The name is regarded as an alias of the first member

class Color(Enum):
    red   = 1
    green = 2
    blue  = 1

print(Color.red)              # Color.red
print(Color.blue)             # Color.red
print(Color.red is Color.blue)# True
print(Color(1))               # Color.red  在通过值获取枚举成员时,只能获取到第一个成员

If you cannot define the same member value, you can decorate it with unique

from enum import Enum, unique
@unique
class Color(Enum):
    red   = 1
    green = 2
    blue  = 1  # ValueError: duplicate values found in <enum>: blue -> red</enum>

Enumeration value

You can get members by member name or member value:

print(Color['red'])  # Color.red  通过成员名来获取成员

print(Color(1))      # Color.red  通过成员值来获取成员

Each member has a name attribute and a value attribute:

member = Color.red
print(member.name)   # red
print(member.value)  # 1

supports iteration through members in the defined order. If there are members with duplicate values, only the first duplicate member is obtained:

for color in Color:
    print(color)

Special attributes__members__ is a An ordered dictionary mapping names to members, through which traversal can also be done:

for color in Color.__members__.items():
    print(color)          # ('red', <color.red:>)</color.red:>

Enumeration comparison

Members of an enumeration can be passed through is Identity comparison or equality comparison through ==:

Color.red is Color.red
Color.red is not Color.blue

Color.blue == Color.red
Color.blue != Color.red

Enumeration members cannot perform size comparison:

Color.red <p><strong> Extended enumeration IntEnum</strong></p><p>IntEnum is an extension of Enum. Different types of integer enumerations can also be compared with each other: </p><pre class="brush:php;toolbar:false">from enum import IntEnum
class Shape(IntEnum):
    circle = 1
    square = 2

class Request(IntEnum):
    post = 1
    get = 2

print(Shape.circle == 1)            # True
print(Shape.circle = Request.post) # True

Summary

enum module function is very clear , its usage is also simple, and its implementation method is worth learning. If you have the opportunity, you can take a look at its source code.

The above is the detailed content of Detailed explanation of enumeration types in Python (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

What are unit tests in Python?What are unit tests in Python?Apr 30, 2025 pm 02:05 PM

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

What are Access Specifiers in Python?What are Access Specifiers in Python?Apr 30, 2025 pm 02:03 PM

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

What is __init__() in Python and how does self play a role in it?What is __init__() in Python and how does self play a role in it?Apr 30, 2025 pm 02:02 PM

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

What is the difference between @classmethod, @staticmethod and instance methods in Python?What is the difference between @classmethod, @staticmethod and instance methods in Python?Apr 30, 2025 pm 02:01 PM

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor