Here's an example of a Python class with a state machine inside. We'll create a simple vending machine class that can be in one of three states: SELECT_PRODUCT, INSERT_COINS, or DISPENSE_PRODUCT.
from enum import Enum
class VendingMachineState(Enum):
"""Enum for vending machine states"""
SELECT_PRODUCT = 1
INSERT_COINS = 2
DISPENSE_PRODUCT = 3
class VendingMachine:
"""Vending machine class with a state machine"""
def __init__(self):
"""Initialize the vending machine"""
self.state = VendingMachineState.SELECT_PRODUCT
self.product_selected = None
self.coins_inserted = 0
def select_product(self, product):
"""Select a product"""
if self.state == VendingMachineState.SELECT_PRODUCT:
self.product_selected = product
self.state = VendingMachineState.INSERT_COINS
print(f"Product {product} selected. Please insert coins.")
else:
print("Invalid state. Please select a product first.")
def insert_coins(self, amount):
"""Insert coins"""
if self.state == VendingMachineState.INSERT_COINS:
self.coins_inserted += amount
if self.coins_inserted >= 10: # assuming the product costs 10 units
self.state = VendingMachineState.DISPENSE_PRODUCT
print("Enough coins inserted. Dispensing product...")
else:
print(f"Coins inserted: {self.coins_inserted}. Please insert more coins.")
else:
print("Invalid state. Please insert coins after selecting a product.")
def dispense_product(self):
"""Dispense the product"""
if self.state == VendingMachineState.DISPENSE_PRODUCT:
print(f"Dispensing product {self.product_selected}.")
self.state = VendingMachineState.SELECT_PRODUCT
self.product_selected = None
self.coins_inserted = 0
else:
print("Invalid state. Please insert coins and select a product first.")
# Example usage:
vending_machine = VendingMachine()
vending_machine.select_product("Soda")
vending_machine.insert_coins(5)
vending_machine.insert_coins(5)
vending_machine.dispense_product()
In this example, the VendingMachine class has a state attribute that is an instance of the VendingMachineState enum. The class has methods for each state transition:
select_product: Transitions from SELECT_PRODUCT to INSERT_COINS.
insert_coins: Transitions from INSERT_COINS to DISPENSE_PRODUCT when enough coins are inserted.
dispense_product: Transitions from DISPENSE_PRODUCT back to SELECT_PRODUCT.
Each method checks the current state before performing the state transition. If the current state is not valid for the method, it prints an error message.
The example usage at the end demonstrates how to use the VendingMachine class.
State Handling Mechanism
The state handling mechanism in this example is based on the following steps:
- Define the states: Enumerate all possible states of the vending machine using an enum (
VendingMachineState).
- Initialize the state: Set the initial state of the vending machine in the
__init__ method (self.state = VendingMachineState.SELECT_PRODUCT).
- Define state transition methods: Create methods for each state transition (e.g.,
select_product, insert_coins, dispense_product).
- Check the current state: In each state transition method, check the current state before performing the state transition.
- Perform the state transition: If the current state is valid, update the state attribute and perform any necessary actions.
- Handle invalid states: If the current state is not valid, print an error message or handle the situation accordingly.
By following these steps, you can implement a state machine in a Python class that handles state transitions and ensures that the object is always in a valid state.