CodexBloom - Programming Q&A Platform

Difficulty Implementing the Strategy Pattern in Python 3.10 for Dynamic Behavior Change

👀 Views: 72 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
python design-patterns oop Python

I'm trying to implement I'm trying to implement the Strategy Pattern in Python 3.10 to dynamically change the behavior of a class during runtime, but I'm running into some confusion about how to properly switch strategies... I have the following code setup: ```python class Strategy: def execute(self): raise NotImplementedError("You should implement this!") class ConcreteStrategyA(Strategy): def execute(self): return 'Strategy A' class ConcreteStrategyB(Strategy): def execute(self): return 'Strategy B' class Context: def __init__(self, strategy: Strategy): self._strategy = strategy def set_strategy(self, strategy: Strategy): self._strategy = strategy def execute_strategy(self): return self._strategy.execute() ``` I create an instance of the `Context` class using `ConcreteStrategyA`: ```python context = Context(ConcreteStrategyA()) print(context.execute_strategy()) # Output: Strategy A ``` However, when I try to change the strategy using the `set_strategy` method: ```python context.set_strategy(ConcreteStrategyB()) print(context.execute_strategy()) # Expected: Strategy B ``` I get an error: **"AttributeError: 'ConcreteStrategyB' object has no attribute 'execute'"**. I've made sure that `ConcreteStrategyB` inherits from `Strategy`, and both `execute` methods are implemented correctly. I've also checked that I am indeed passing the correct class type to `set_strategy`. Is there something I'm missing in how I'm using the Strategy Pattern? Any insights on how to resolve this would be greatly appreciated! I'm working on a mobile app that needs to handle this. The stack includes Python and several other technologies. Any feedback is welcome! This is part of a larger service I'm building.