Description:
- Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.
- For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2).
- To use enum34, do $ pip install enum34
- To use aenum, do $ pip install aenum
Program:
# Python enum usage
# Check : http://velrajcoding.blogspot.in
#
# Below is supported from python 3.4 onwards.
from enum import Enum
class Animal(Enum):
DOG = 1
CAT = 2
LION = 3
class EnumAssign():
def __init__(self):
self.Animal_enum = Animal
def display_ani(self, value):
print("The EnumAssign Animal.DOG : ")
print(self.Animal_enum.DOG)
print("The EnumAssign Animal.DOG value : %d" % self.Animal_enum.DOG.value)
print("The EnumAssign Animal.DOG name : %s" % self.Animal_enum.DOG.name)
if self.Animal_enum.DOG.value == value:
print("The requested value is DOG")
elif (self.Animal_enum.CAT.value == value):
print("The requested value is CAT")
elif (self.Animal_enum.LION.value == value):
print("The requested value is LION")
def main():
print()
print("****************** Starting Main fun ******************************")
print()
obj = EnumAssign();
obj.display_ani(Animal.CAT.value)
#print("The value of enum is : %d " % Animal.DOG)
print("The display Outside function Direct access Animal.DOG : ")
print(Animal.DOG)
print("The display Outside function Direct access Animal.DOG value : %d" % Animal.DOG.value)
print("The display Outside function Direct access Animal.DOG name : %s" % Animal.DOG.name)
if __name__ == "__main__":
main()
Output
h]$ python3 py_enum.py
The display Outside function Direct access Animal.DOG :
Animal.DOG
The display Outside function Direct access Animal.DOG value : 1
The display Outside function Direct access Animal.DOG name : DOG
****************** Starting Main fun ******************************
The EnumAssign Animal.DOG :
Animal.DOG
The EnumAssign Animal.DOG value : 1
The EnumAssign Animal.DOG name : DOG
The requested value is CAT