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
Susan SarandonOriginal
2024-12-20 06:16:08972browse

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
  2. Define the enumeration:

    Animal = enum.Enum('Animal', 'ant bee cat dog')
  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)

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

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

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)

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']

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!

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