what is enum python

Jun 22, 2019 am 10:38 AM
enumerate

what is enum python

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. 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 In the implementation of simple enumeration types, 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 the implementation. Its normal use:

WEEKDAY['MON'] = WEEKDAY['FRI']
  print(WEEKDAY)
  {'FRI': 5, 'TUS': 2, 'MON': 5, 'WEN': 3, 'THU': 4}
  通过类定义的枚举甚至可以实例化,变得不伦不类:
  c = Color()
  print(c.RED)
  Color.RED = 2
  print(c.RED)
  0
  2
Copy after login

Of course, you can also use immutable types (immutable), such as tuples, but this loses the original intention of the enumeration type and degrades the label into a meaningless variable:

COLOR = ('R', 'G', 'B')
  print(COLOR[0], COLOR[1], COLOR[2])
  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 and supported libraries through pip install enum. enum provides three tools: Enum/IntEnum/unique, and their usage is very simple. You can define enumeration types by inheriting Enum/IntEnum. 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 value of the enumeration member to be non-repeatable:

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

The above is the detailed content of what is enum python. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Python program to find enum by string value Python program to find enum by string value Sep 21, 2023 pm 09:25 PM

An enumeration in Python is a user-defined data type that consists of a named set of values. A finite set of values ​​is defined using an enumeration, and these values ​​can be accessed in Python using their names instead of integer values. Enumerations make code more readable and maintainable, and they also enhance type safety. In this article, we will learn how to find an enumeration by its string value in Python. To find an enum by a string value we need to follow these steps: Import the enum module in your code Define the enum with the required set of values ​​Create a function that takes the enum string as input and returns the corresponding enum value . Syntax fromenumimportEnumclassClassName(Enum

What are the benefits when a C++ function returns an enumeration type? What are the benefits when a C++ function returns an enumeration type? Apr 20, 2024 pm 12:33 PM

Benefits of using enumeration types as function return values: Improve readability: Use meaningful name constants to enhance code understanding. Type safety: Ensure return values ​​fit within the expected range and avoid unexpected behavior. Save memory: Enumerated types generally take up less storage space. Easy to extend: New values ​​can be easily added to the enumeration.

How to use enumerations in C/C++? How to use enumerations in C/C++? Aug 28, 2023 pm 05:09 PM

Enumeration is a user-defined data type in C language. It is used to give names to integer constants, making programs easier to read and maintain. The keyword "enum" is used to declare an enumeration. The following is the syntax of enumerations in C language: enumenum_name{const1,const2,.....};Theenumkeywordisalsousedtodefinethevariablesofenumtype.Therearetwowaystodefinethevariablesofenumtypeasfollows.enumweek{sunday,monday,tuesday,

C++ syntax error: Enumeration members need to be initialized within parentheses, what should I do? C++ syntax error: Enumeration members need to be initialized within parentheses, what should I do? Aug 22, 2023 pm 03:41 PM

C++ is a common programming language whose syntax is relatively rigorous and easy to learn and apply. However, during specific programming, it is inevitable to encounter various errors. One of the common errors is "enumeration members need to be initialized within parentheses". In C++, the enumeration type is a very convenient data type that can define a set of constants with discrete values, such as: enumColor{RED,YELLOW,GREEN}; In this example, we define an enumeration Type Color, which contains three enumerations

Java program accesses all constants defined in an enumeration Java program accesses all constants defined in an enumeration Aug 19, 2023 pm 04:29 PM

After JDK version 5, Java introduced enumerations. It is a set of constants defined using the keyword 'enum'. In Java, final variables are somewhat similar to enumerations. In this article, we will create a Java program in which we define an enumeration class and try to access all the constants defined in the enumeration using valueOf() and values() methods. The Chinese translation of Enum is: Enumeration. When we need to define a fixed set of constants, we use the enumeration class. For example, if we want to use the days of the week, the names of the planets, the names of the five vowels, etc. Note that the names of all constants are declared in uppercase letters. Although in Java, enumeration is a class type, we cannot instantiate it. exist

Enumeration types in Java Enumeration types in Java Jun 15, 2023 pm 08:46 PM

Java is an object-oriented programming language that provides rich syntax and built-in types. An enumeration type in Java is a special type that allows the programmer to define a fixed collection of values ​​and assign a name to each value. Enumeration types provide a simple, safe, and readable way to represent a group of related constants. The enumeration type in Java is a reference type, which was introduced in JavaSE5. The definition of an enumeration type uses the keyword "enum" to list all enumeration constants in the definition. Every

C++ syntax error: identifiers in enumerations must be integer constants, how to solve it? C++ syntax error: identifiers in enumerations must be integer constants, how to solve it? Aug 22, 2023 am 10:27 AM

When programming in C++, sometimes you will encounter the syntax error message "Identifiers in enumerations must be integer constants". This article explains the causes of this problem and possible solutions. First, we need to clarify what an enumeration is. In C++, an enumeration is a special data type used to define a collection of constants with discrete values. Each constant in the enumeration is assigned an integer value, with the first constant defaulting to 0 and the remaining constants incrementing in sequence. For example: enumWeekday{Monday,Tues

See all articles