from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 # Example usage: print(Color.RED) print(Color.GREEN) print(Color.BLUE)
Color.RED Color.GREEN Color.BLUE
# Access by name print(Color.RED.name) # Output: RED print(Color.RED.value) # Output: 1 # Access by value print(Color(1)) # Output: Color.RED
RED 1 Color.RED
for color in Color: print(f"{color.name} = {color.value}")
RED = 1 GREEN = 2 BLUE = 3
# Comparing members print(Color.RED == Color.RED) # Output: True print(Color.RED is Color.RED) # Output: True print(Color.RED == Color.GREEN) # Output: False # Enum members can also be compared using their values print(Color.RED.value == 1) # Output: True print(Color.RED.value == 2) # Output: False
True True False True False
from enum import Enum class StatusCode(Enum): SUCCESS = 200 NOT_FOUND = 404 SERVER_ERROR = 500 # Example usage: print(StatusCode.SUCCESS) # Output: StatusCode.SUCCESS print(StatusCode.SUCCESS.value) # Output: 200
StatusCode.SUCCESS 200
from enum import Enum, auto class Animal(Enum): DOG = auto() CAT = auto() HORSE = auto() # Example usage: print(Animal.DOG.value) # Output: 1 print(Animal.CAT.value) # Output: 2 print(Animal.HORSE.value) # Output: 3
1 2 3
from enum import Enum class Operation(Enum): ADD = "+" SUBTRACT = "-" MULTIPLY = "*" DIVIDE = "/" def describe(self): return f"This is an operation for {self.name}." def apply(self, a, b): if self == Operation.ADD: return a + b elif self == Operation.SUBTRACT: return a - b elif self == Operation.MULTIPLY: return a * b elif self == Operation.DIVIDE: return a / b # Example usage: op = Operation.ADD print(op.describe()) # Output: This is an operation for ADD. print(op.apply(4, 2)) # Output: 6
This is an operation for ADD. 6
from enum import Flag, auto class Permission(Flag): READ = auto() WRITE = auto() EXECUTE = auto() # Example usage: perm = Permission.READ | Permission.WRITE print(perm) # Output: Permission.READ|WRITE print(Permission.READ in perm) # Output: True print(Permission.EXECUTE in perm) # Output: False
Permission.WRITE|READ True False
from enum import Enum class Weekday(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 # Alias MON = MONDAY # Example usage: print(Weekday.MON) # Output: Weekday.MONDAY print(Weekday.MON.name) # Output: MONDAY print(Weekday.MON.value) # Output: 1
Weekday.MONDAY MONDAY 1
from enum import Enum class Role(Enum): USER = "user" ADMIN = "admin" GUEST = "guest" # Example usage: print(Role.USER) # Output: Role.USER print(Role.USER.value) # Output: user
Role.USER user
from enum import Enum, auto class Ordinal(Enum): def _generate_next_value_(name, start, count, last_values): return name.lower() FIRST = auto() SECOND = auto() THIRD = auto() # Example usage: print(Ordinal.FIRST) # Output: Ordinal.first print(Ordinal.SECOND) # Output: Ordinal.second print(Ordinal.THIRD) # Output: Ordinal.third
Ordinal.FIRST Ordinal.SECOND Ordinal.THIRD