C++ enum instance equivalent in Python

This question already has an answer here:

  • How can I represent an 'Enum' in Python? 43 answers

  • Here's what i found:

    How can I represent an 'Enum' in Python?

    tl;dr:

    class Animal:
    DOG = 1
    CAT = 2
    
    x = Animal.DOG
    

    Until Python 3.4, the Pythonic approach would be to just use integers:

    MODE_UPPERCASE, MODE_LOWERCASE, MODE_PUNCTUATION = range(3)
    
    mode = MODE_UPPERCASE
    
    switch_mapping = {
        MODE_UPPERCASE: handle_upper,
        # etc.
    }
    

    If you are using 3.4 or newer, you can use the new enum library:

    from enum import Enum
    
    Mode = Enum('Mode', 'uppercase lowercase punctuation')
    mode = Mode.uppercase
    
    switch_mapping = {
        Mode.uppercase: handle_upper,
        # etc.
    }
    

    The enumeration values are still integers in this case (as the functional API I used here auto-assigns integers from 1).


    In python 3 you juste have to do this:

    from enum import Enum
    
    class modeType(Enum):
        UPPERCASE       =1
        LOWERCASE       =2
        PUNCTUATION =3
    

    See the official : https://docs.python.org/3/library/enum.html

    链接地址: http://www.djcxy.com/p/91744.html

    上一篇: 有没有什么办法来定义在Python中的枚举?

    下一篇: Python中的C ++枚举实例