Are you looking for customized advices? Click here to contact the expert!
by
827 22
3
4
345
2
Top 1% !
Tagged
Specified
MultiPlatform
Popularity: 9642nd place
Created
Modified May 3, 2016
Languagepython
LicenseMIT_X11

Command pattern

Look ma, no objects!
post this code
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/1198167/Command-pattern?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
# Command Pattern # using only functions which are "first-class citizen" in Python # and therefore they can be passed around # do something actually def say(msg): print(msg) # action functions def meauw(): say("meauw") def woof(): say("woof") def neigh(): say("nyihaha!!!") # command -> action mapping actions = { "cat": meauw, "dog": woof, "horse": neigh, } def handle(command): """ the command executioner... whoohaahaa! :) """ action = actions.get(command,None) if action: # existing command action() # execute command else: # no command found say("Sorry! No %s here." % command) # no such command! for cmd in ["cat", "horse", "dog", "elephant"]: handle(cmd)
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus