Enum class in PythonWhat is an Enum?In Python, an enumeration is a set of named values that address a finite set of conceivable outcomes. For example, assuming that we were composing a program that expected to address the days of the week, we could characterize an enumeration with seven named values: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday. An enumeration permits you to work with these values in a more significant manner than basically utilizing strings or integers. For example, you could analyse two days of the week utilizing the == operator, and it would function true to form: Characteristics of enum:
Example: Enum class for creating enumerationsOutput: The member of Enum class as the string is : Weekdays.Monday The member of Enum class as a repr is : Example 2: How to print Enum as an Iterable listThe users can print the Enum class as an iterable list. In the following example, we will use for loop to print all the members of the Enum class. Code Output: The member of Enum class are : Weekdays.Sunday Weekdays.Monday Weekdays.Tuesday Weekdays.Wednesday Weekdays.Thursday Weekdays.Friday Weekdays.Saturday Example 3: How to Hash Enum ClassThe members of the Enum class are called Enumeration, and also hashable. Therefore, these members can be used for sets and dictionaries. Code Output: Enum class is hashed Example 4: How to access Enum membersThe users can access the members of the Enum class by using the value or the name of the member items. The name of the Enum is used as an index. Code Output: The member of Enum class accessed by name: Days.Monday The member of Enum class accessed by name: Days.Friday The member of Enum class accessed by Value: Days.Sunday The member of Enum class accessed by Value: Days.Thursday Example 5: How to Compare the EnumsTo compare the Enums, We use the following methods:
Code Output: Match Do not Match Match Do not Match ConclusionIn this article, we've explored the enum class in Python, which permits us to characterize and work with enumerations in our code. By utilizing an enumeration, we can make your code more coherent and less mistake inclined, while likewise giving extra sort security. Next TopicDestructors in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India