Note that what function we call now depends entirely on what the value is of command. Say a network process sends you command codes, a dispatch mapping lets you translate the command codes easily into executable code: def do_ping(self, arg):ĭef process_network_command(command, arg): Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a function. The key doesn't need to be hardcoded though, as in your example. Using a dict let's you translate the key into a callable. > find_city (cities, 'New York')Ĭan someone explain what language feature this is, and maybe where it comes to play in "real" programming? This toy exercise was enough to teach me the syntax, but didn't take me all the way there. You can call the function directly, or by referencing the dict element whose value is the function. Then the following expressions are equivalent. # then add a final dict element that refers to the function # define a function to use on such a dictionary To paraphrase: # make a dictionary of US states and major citiesĬities = (This is the version available when you sign up through sadly the live free HTML version is currently Ed 3, and no longer includes this example). The example I'm working from is from Learn Python the Hard Way, 2nd Ed. When you're ready to call the function you issue the call indirectly by referring to the dict element, not the function by name. You insert an extra element into the dict, whose value is the name of the function. The technique is when you have a python dictionary and a function that you intend to use on it. Can someone put a name to this technique and explain how/why it's useful? Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. I'm a python beginner, and I just learned a technique involving dictionaries and functions.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |