26. Enumerations (Enums):

This Python code snippets that demonstrate the usage of Enumerations (Enums) using Python's enum module to define symbolic names for unique constant values.

1. Basic Enum Example

Copy

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)  # Color.RED
print(Color.RED.value)  # 1
print(Color.RED.name)  # RED

2. Iterating Over Enums

Copy

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3

for day in Day:
    print(day.name, day.value)
# Output:
# MONDAY 1
# TUESDAY 2
# WEDNESDAY 3

3. Comparison of Enums

Copy


4. Accessing Enum Members Dynamically

Copy


5. Enums with Non-Integer Values

Copy


6. Unique Enums Using @unique

Copy


7. Auto Assigning Values to Enums

Copy


8. Enum with Methods

Copy


9. Extending Enums with Additional Attributes

Copy


10. Flag Enum for Bitwise Operations

Copy


These examples highlight the power and versatility of Python's enum module, which makes code more readable, organized, and maintainable by providing symbolic names for constant values.

Last updated