enum python code example
Example 1: javascript enum
const seasons = {
SUMMER: {
BEGINNING: "summer.beginning",
ENDING: "summer.ending"
},
WINTER: "winter",
SPRING: "spring",
AUTUMN: "autumn"
};
let season = seasons.SUMMER.BEGINNING;
if (!season) {
throw new Error("Season is not defined");
}
switch (season) {
case seasons.SUMMER.BEGINNING:
// Do something for summer beginning
case seasons.SUMMER.ENDING:
// Do something for summer ending
case seasons.SUMMER:
// This will work if season = seasons.SUMMER
// Do something for summer (generic)
case seasons.WINTER:
//Do something for winter
case seasons.SPRING:
//Do something for spring
case seasons.AUTUMN:
//Do something for autumn
}
Example 2: enum in python
import enum
# Using enum class create enumerations
class Days(enum.Enum):
Sun = 1
Mon = 2
Tue = 3
# print the enum member as a string
print ("The enum member as a string is : ",end="")
print (Days.Mon)
# print the enum member as a repr
print ("he enum member as a repr is : ",end="")
print (repr(Days.Sun))
# Check type of enum member
print ("The type of enum member is : ",end ="")
print (type(Days.Mon))
# print name of enum member
print ("The name of enum member is : ",end ="")
print (Days.Tue.name)
Example 3: python env
python3 -m venv tutorial-env
tutorial-env\Scripts\activate.bat (window)
source tutorial-env/bin/activate (linux)
Example 4: enum python
>>> from enum import Enum
>>> class Color(Enum):
... RED = 1
... GREEN = 2
... BLUE = 3
...
Example 5: get value from enum python
print(D.x.value)
Example 6: python enums
import enum
class Days(enum.Enum):
Sun = 1
Mon = 2
Tue = 3
print ("The enum members are : ")
for weekday in (Days):
print(weekday)
# The enum members are :
# Days.Sun
# Days.Mon
# Days.Tue
best_day = Days.Sun
worst_day = Days(2)
print(best_day) # Days.Sun
print(worst_day) # Days.Mon