Implementation enum in Python
In this article, we will discuss the Implementation of enum in Python. The main functionality of the enum is to create Enumerations.
enum in Python:
First of all, enum is a class had been used to define the multiple members which are assigned by the constant (or) individual values. The main aim of the enum class is creating enumerations.
Characteristics of enum:
- The name enum can be viewed by the name keyword.
- The displayed enum is in the form of either string or repr().
- type() method is used to check the enum type.
Example of enum
import enum #creating enumerations class A(enum.Enum): d=1 c=2 l=3 #printing enum as a string print("The string representation of enum member is:",end='') print(A.d) #printing enum member as repr print("The repr representation of enum member is:",end='') print(repr(A.d)) #printing the type of enum member using type() print("The type of enum member is:",end='') print(type(A.d)) #printing name of enum member using 'name' keyword print("The name of enum member is:,end='') print(A.d.name)
Output:
consequently, the result is:
The string representation of enum member is: A.d The repr representation of enum member is: <A.d: 1> The type of enum member is: <enum 'A'> The name of enum member is: d
Printing enum as an iterable:
Using loops we can iterate the enum list members.
So, we use for loop to print members in the enum class.
For Example:
import enum class D(enum.Enum): a=1 b=2 c=3 print("The enum members are:") for i in (D): print(i)
Output:
Consequently, the result of the above code is:
The enum members are: D.a D.b D.c
Hashing enums:
Enumerations (or) enum members can be hashing. Dictionaries or sets had been used in the enum class.
import enum class A(enum.Enum): d=1 c=2 l=3 di={} di[A.d]='codespeedy' di[A.l]='python' if(di=={A.d:'codespeedy',A.l:'Python'}): print("Hashed") else: print("Not Hashed")
Output:
Consequently, the result of the above code is:
Hashed
Accessing enums:
Enum accessed in two ways
- Using name: The name of the enum member is passed as a parameter.
- Using value: The value of the enum member is passed as a parameter.
For Example:
import enum class D(enum.Enum): s=1 m=2 print('accessed by name:') print(D['m']) print('accessed by value:) print(D(1))
Consequently, the result is:
accessed by name: D.m accessed by value: D.s
Comparing the enum:
Comparison operator is mainly used to comparing enums.
For Example:
import enum class D(enum.Enum): s=1 m=2 t=1 if(D.s==D.t): print('match') if(D.m!=D.t): print('no match')
Output:
Consequently, the result is:
match no match
Above all, programs are some of the methods of Implementation enum in Python.
Finally, for more reference:
Leave a Reply