Saturday 11 September 2021

Python: access the enum members

Access enum members by name

Using item access approach, you can access the enum members by name.

 

Example

Color['RED'] # this way is used to access programmatically, when you do not have the information at compile time.
Color.RED

 

accessEnumMembersByName.py

from enum import Enum

class Color(Enum):
    RED = 121
    GREEN = 255
    BLUE = 30

print(Color['RED'])
print(Color['GREEN'])
print(Color['BLUE'])

Output

Color.RED
Color.GREEN
Color.BLUE


Access enum members by value

‘Enum(value)’ return the enum member associated with this value.

 

accessEnumMemberByValue.py

from enum import Enum

class Color(Enum):
    RED = 121
    GREEN = 255
    BLUE = 30

print(Color(121))
print(Color(255))
print(Color(30))


Output

Color.RED
Color.GREEN
Color.BLUE


Problem while accessing the enum member by value

Suppose if more than one enum member has same value, accessing by value always return the first matched member.

 

accessEnumMemberByValue1.py


from enum import Enum

class Color(Enum):
    RED = 121
    GREEN = 255
    BLUE = 255

print(Color(121))
print(Color(255))
print(Color(255))


Output

Color.RED
Color.GREEN
Color.GREEN




 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment