Application of Python 3 enum module

Keywords: Python Attribute

python Enumeration Module Learning

ps: Xiaobian has just started to study for a short time. Some resources come from other netizens. If there are any mistakes, please contact and modify Kazakhstan, help each other and make progress together.

Enumeration and Dictionary Types

Disadvantages of dictionary type: 1. Variable value 2. No function to prevent the same label

The characteristics of enumeration: 1. The value of enumeration class can not be changed by the outside world 2. The same label cannot exist, but different labels can be allowed to have the same enumeration value, that is, the latter is equivalent to the alias of the former 3. The enumeration value can be of any type 4. Enumeration labels should be capitalized as far as possible.

from enum import Enum  #General category

class dict():
    green = 1
    green = 2
    red = 3

dict.red = 4   
print(dict.red)

>>> 4

 

 

class VIP(Enum): 
    RED = 1
    GREEN =2
    YELLOW = 3

VIP.GREEN = 5  #Enumeration values cannot be changed dynamically

>>>File "D:\python\lib\enum.py", line 361, in __setattr__

  raise AttributeError('Cannot reassign members.')

  AttributeError: Cannot reassign members.
class VIP(Enum):
    RED = 1
    GREEN =2
    YELLOW = 3
    YELLOW = 3  #The same label cannot appear

>>>File "D:\python\lib\enum.py", line 92, in __setitem__
       raise TypeError('Attempted to reuse key: %r' % key)
       TypeError: Attempted to reuse key: 'YELLOW'
class VIP(Enum):
    RED = 1
    GREEN =2
    YELLOW = 3
    BLUE = 3

print(VIP.BLUE)

"> VIP.YELLOW # that is, VIP.BLUE is similar to the alias of VIP.YELLOW
class VIP(Enum):
    RED = 1  #integer
    BLUE = 1.2 #float
    GREEN = 'green'  #str
    YELLOW = True  #Boolean value

Enumeration Type, Enumeration Name, Enumeration Value

1. Get the label:. name attribute in the enumeration type

2. Get the value in the enumeration type:.Value attribute

from enum import Enum
class VIP(Enum):
    RED = 1
    GREEN = 'green'
    YELLOW = True
    BLUE = 1.2

print(VIP.RED)  #Types of enumeration
print(VIP.YELLOW.name)    #Enumerated labels
print(VIP.YELLOW.value)    #Enumerated values
print('Traverse members...')
for i in VIP.__members__.items():    #Enumeration traversal
    print(i)

>>>
VIP.RED
RED
1
//Traverse members...
('RED', <VIP.RED: 1>)
('GREEN', <VIP.GREEN: 'green'>)
('YELLOW', <VIP.RED: 1>)
('BLUE', <VIP.BLUE: 1.2>)

3. Enumeration Comparisons

class VIP(Enum):
    RED = 1
    GREEN = 'green'
    YELLOW = True
    BLUE = 2
#Enumeration comparison
a = VIP.RED == VIP.RED  #Enumeration values can be compared by equivalence
b = VIP.RED == VIP.GREEN
c = VIP.RED is VIP.RED
d = VIP.RED == 1  #Enumeration labels are not equal to enumeration values
f = VIP.RED < VIP.BLUE  #Enumeration values do not support size comparison, printing will report errors TypeError: '<' not supported between instances of 'VIP' and 'VIP'

print(a)
print(b)
print(c)
print(d)

>>>
True
False
True
False

IV. Conversion of Enumeration

class VIP(Enum):
    RED = 1
    GREEN = 'green'
    YELLOW = True
    BLUE = 2

print(VIP(2))   #Get the enumeration type by the specific value, and return VIP.BLUE
print(VIP('green'))    #Return VIP.GREEN

5. Expansion of enumeration unique

unique: Provides that two different enumerations cannot take the same value

from enum import Enum,unique

@unique
class VIP(Enum):
    RED = 1
    GREEN = 1
    YELLOW = True
    BLUE = 2

>>>Report errors
ValueError: duplicate values found in <enum 'VIP'>: GREEN -> RED, YELLOW -> RED

6. Expansion of enumeration auto

If we don't have special requirements for enumeration values or have little impact on them, we can use auto to automatically generate the corresponding values.

 

from enum import Enum,auto

class VIP(Enum):
    RED = auto()
    GREEN = auto()
    YELLOW = auto()
    BLUE = auto()

for i in VIP.__members__.items():   #Ergodic enumeration
    print(i)

>>>
('RED', <VIP.RED: 1>)
('GREEN', <VIP.GREEN: 2>)
('YELLOW', <VIP.YELLOW: 3>)
('BLUE', <VIP.BLUE: 4>)

 

In fact, the auto value is generated by calling the _generate_next_value_() function, which we can override.

from enum import Enum,auto

class auto_test(Enum):
    def _generate_next_value_(name, start, count, last_values):
        return name

class VIP(auto_test):
    RED = auto()
    GREEN = auto()
    YELLOW = auto()
    BLUE = auto()

# for i in VIP.__members__.items():  #Ergodic enumeration
#     print(i)
print(list(VIP))   #Conversion list

>>>
[<VIP.RED: 'RED'>, <VIP.GREEN: 'GREEN'>, <VIP.YELLOW: 'YELLOW'>, <VIP.BLUE: 'BLUE'>]

Posted by router on Mon, 07 Oct 2019 14:53:02 -0700