This is the 13th day of my participation in Gwen Challenge

The business scenario

As we all know, enumeration is a very important concept in the development of our large outsourcing company and can be enumerated in countless usage scenarios:

  1. Whether to delete attributes in logical deletion
  2. Type-related attributes in a business
  3. State correlation in a process

For the Chinese nation, enumeration is missing an important part, whether in Java or Python, which is its Chinese meaning

This article will take a brief look at the use of enumerations in Python and then derive them to create an enumeration class suitable for our business scenario

plan

The enumeration section of the Official Python Chinese documentation is linked here. If you need to check it out, the following content is my summary

Enum and IntEnum

Creating enums in Python is simple, such as states:

from enum import Enum

class Status(Enum) :
    STOP = -1
    INIT = 0
    START = 1
Copy the code

Where STOP/INIT/START is the name of the enumeration and -1/0/1 is the value of the enumeration

We can use status.stop. name to get the name of the enumeration, and status.stop. value to get the value of the enumeration

Enumerations can be compared, such as status.stop == status.init, which results in False

Note that status.stop == -1 results in False

This leads to another enumeration, IntEnum

It can be compared directly to an integer. If Status inherits IntEnum, then status. STOP == -1 equals True

IntEnum still cannot be compared to Enum

Custom NameEnum

When presenting enumerations on the front end, Chinese is required in most cases

I strongly recommend that both the front and back end maintain the same set of enumerations; all data-related content (enumerations/dictionaries, etc.) should be handed over to the back end interface

In Python, we can use the enumeration’s __new__ method to implement this, directly to the code:

from enum import IntEnum


class NameEnum(IntEnum) :
    def __new__(cls, value, desc) :
        obj = int.__new__(cls)
        obj._value_ = value
        obj.desc = desc
        return obj
Copy the code

We derive a NameEnum based on IntEnum, and its __new__ method takes an desc parameter, which is used to record the Chinese description of the enumeration. Then we modify the previous Status:

class Status(NameEnum) :
    STOP = (-1.'stop')
    INIT = (0.'initialize')
    START = (1.'start')
Copy the code

So we can use the description of enumeration:

print(Status.INIT.name) // STOP
print(Status.INIT.value) // 0
print(status.init.desc) // InitializationCopy the code