With all the posts about Objective-C and design patterns lately that David’s been posting, it’s only fair that we bring back some of it to Python with some simple patterns. So, let’s steal the strategy pattern post today!
Thanks to Python’s first-class functions, we essentially get them for free.
<python>
1 2 3 4 | class MagicButton(object): def __init__(some_function): #bind some_function to press self.press = some_function |
Now, so long as some_function supports __call__ that is, it supports the use of () stuck next to it, you can call self.press() as appropriate.
And while we’re at it, we’ll mix the things into a list that can act as a queue or something.
1 2 3 4 5 6 7 8 9 10 11 | a = MagicButton(jump) b = MagicButton(hop) #make some buttons, for x in [a,b]:#list them x.press() #and press #or... #make a list of actions.. for x in [a.press, b.press] x() #and run... |
While scribbling this down, David challenged me to come up with imitating the forwarding feature of his article. Since I don’t work with Obj-C it took a while to read the code… then longer to wonder why exactly would I want to do it in Python… After all, we can pass whatever we want to a function using *args, **kwargs
1 2 3 4 5 6 7 | def fireworks(*args,**kwargs): for x in args: print x for k, y in kwargs: print k, y a = MagicButton(fireworks) a.press(20, explosions=3)#just send in whatever! a.press(12,52,3, duds=255, fatal_accidents=4)#it'll still take it... |
At which point, if you’re feeding your functions bad data and it throws on you, that’s your fault, right?