To implement an enum with associated data in Python, you can leverage the enum module and define custom attributes for each enum member. This approach allows you to associate additional data (such as descriptions, colors, prices, or other metadata) with each enum value, making your code more expressive and maintainable.
✅ Key Concepts
Python’s enum.Enum class allows you to define constants with names and values.
You can assign complex data (like tuples, dictionaries, or objects) to each enum member.
To access this data, define an __init__ method inside your enum class to initialize attributes based on the provided data.
🧠 Example: Fruits with Color and Price
python
from enum import Enum
class Fruit(Enum):
def __init__(self, color, price):
self.color = color
self.price = price
APPLE = 'red', 0.5
BANANA = 'yellow', 0.3
ORANGE = 'orange', 0.7
🔍 How It Works
Each enum member (APPLE, BANANA, etc.) is assigned a tuple of values.
The __init__ method is called with these tuple values as arguments.
The method initializes instance attributes like color and price.