Skip to content

Commit c695dd5

Browse files
committed
Fixed PEP-8 discrepancy in Strategy pattern
1 parent 557677b commit c695dd5

File tree

1 file changed

+20
-16
lines changed

1 file changed

+20
-16
lines changed

strategy.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,40 @@
1-
"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia"""
1+
"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia
22
3-
import types
3+
In most of other languages Strategy pattern is implemented via creating some base strategy interface/abstract class and
4+
subclassing it with a number of concrete strategies (as we can see at http://en.wikipedia.org/wiki/Strategy_pattern),
5+
however Python supports higher-order functions and allows us to have only one class and inject functions into it's
6+
instances, as shown in this example.
7+
"""
8+
import types
49

510

611
class StrategyExample:
7-
8-
def __init__(self, func=None):
9-
self.name = "Strategy Example 0"
10-
if func:
12+
def __init__(self, func=None):
13+
self.name = 'Strategy Example 0'
14+
if func is not None:
1115
self.execute = types.MethodType(func, self)
1216

1317
def execute(self):
1418
print(self.name)
1519

1620

17-
def executeReplacement1(self):
18-
print(self.name + " from execute 1")
21+
def execute_replacement1(self):
22+
print(self.name + ' from execute 1')
1923

2024

21-
def executeReplacement2(self):
22-
print(self.name + " from execute 2")
25+
def execute_replacement2(self):
26+
print(self.name + ' from execute 2')
2327

2428

25-
if __name__ == "__main__":
29+
if __name__ == '__main__':
2630
strat0 = StrategyExample()
2731

28-
strat1 = StrategyExample(executeReplacement1)
29-
strat1.name = "Strategy Example 1"
32+
strat1 = StrategyExample(execute_replacement1)
33+
strat1.name = 'Strategy Example 1'
3034

31-
strat2 = StrategyExample(executeReplacement2)
32-
strat2.name = "Strategy Example 2"
35+
strat2 = StrategyExample(execute_replacement2)
36+
strat2.name = 'Strategy Example 2'
3337

34-
strat0.execute()
38+
strat0.execute()
3539
strat1.execute()
3640
strat2.execute()

0 commit comments

Comments
 (0)