Saturday, 11 September 2021

Python: enum: hello world

In this post, I am going to explain how to define an enum.

 

An enum can be define by extending Enum class.

 

Step 1 : Import Enum class from enum module.

from enum import Enum

 

Step 2: Define enum by extending Enum class

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

 

Find the below working application.

 

helloWorld.py

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

for day in Day:
    print(day)

 

Output

Day.MONDAY
Day.TUESDAY
Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
Day.SUNDAY

 

Points to note

a.   In the above example, class Day represents an enum.

b.   Day.MONDAY, Day.TUESDAY….are the enumeration members or attributes of the enum.

c.    Enumeration members has a value associated with them, for example, Day.SUNDAY has the value 7.

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment