How to create an enumeration of constants with and without explicit values in Python

3 Answers

0 votes
import enum      

class Test(enum.Enum):          
    python = 3          
    java = 1          
    php = 7         
    flag = 0          
    
    
print('{}'.format(Test.python.name))      
print('{}'.format(Test.python.value))
 
 
      
'''
run:
  
python
3
 
'''

 



answered Apr 29, 2019 by avibootz
0 votes
import enum      

class Test(enum.Enum):          
    python = 3          
    java = 1          
    php = 7         
    flag = 0          
    
    
for e in Test:         
    print('{:7} = {}'.format(e.name, e.value))
 
 
      
'''
run:
  
python  = 3
java    = 1
php     = 7
flag    = 0
 
'''

 



answered Apr 29, 2019 by avibootz
0 votes
"""
Title: Enumeration of Constants in Python
Example with and without explicit values
"""

from enum import Enum, auto

# ---------------------------------------------------------
# Enum WITHOUT explicit values (using auto())
# Python automatically assigns increasing values
# ---------------------------------------------------------
class Color(Enum):
    RED = auto()     # 1
    GREEN = auto()   # 2
    BLUE = auto()    # 3

# ---------------------------------------------------------
# Enum WITH explicit values
# ---------------------------------------------------------
class Status(Enum):
    OK = 1
    WARNING = 5
    ERROR = 6
    CRITICAL = 10

# ---------------------------------------------------------
# Demonstration
# ---------------------------------------------------------
print("Enum without explicit values:")
print("RED =", Color.RED.value)
print("GREEN =", Color.GREEN.value)
print("BLUE =", Color.BLUE.value)

print("\nEnum with explicit values:")
print("OK =", Status.OK.value)
print("WARNING =", Status.WARNING.value)
print("ERROR =", Status.ERROR.value)
print("CRITICAL =", Status.CRITICAL.value)



'''
run:

Enum without explicit values:
RED = 1
GREEN = 2
BLUE = 3

Enum with explicit values:
OK = 1
WARNING = 5
ERROR = 6
CRITICAL = 10

'''

 



answered Apr 26 by avibootz

Related questions

...