Home > Backend Development > Python Tutorial > How Do I Implement and Use Enumerations in Python?

How Do I Implement and Use Enumerations in Python?

Susan Sarandon
Release: 2024-12-20 06:16:08
Original
975 people have browsed it

How Do I Implement and Use Enumerations in Python?

Implementing Enumerations in Python

Python provides a built-in enum module in Python 3.4 or above. This module allows for the representation of enumerations, which are collections of named constants. To use it, you can follow these steps:

  1. Import the enum module:

    import enum
    Copy after login
  2. Define the enumeration:

    Animal = enum.Enum('Animal', 'ant bee cat dog')
    Copy after login
  3. Access the members of the enumeration:

    Animal.ant  # returns <Animal.ant: 1>
    Animal['ant']  # returns <Animal.ant: 1> (string lookup)
    Animal.ant.name  # returns 'ant' (inverse lookup)
    Copy after login

Alternatively, you can define an enumeration using a class-based approach:

class Animal(enum.Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4
Copy after login

Earlier Versions of Python

In earlier versions of Python, you can create your own custom enum functionality using a class:

class Enum(object):
    def __init__(self, *args):
        self.keys = args

    def __getattr__(self, attr):
        try:
            return attr, self.keys.index(attr)
        except:
            raise AttributeError(attr)
Copy after login

Using typing.Literal in MyPy

When using MyPy for type checking, you can also express enumerations using typing.Literal:

from typing import Literal

Animal: Literal['ant', 'bee', 'cat', 'dog']
Copy after login

The above is the detailed content of How Do I Implement and Use Enumerations in Python?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template