Timeline for Why store a function inside a python dictionary?
Current License: CC BY-SA 3.0
10 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Dec 17, 2020 at 13:44 | comment | added | Martijn Pieters |
@LoBellin: absolutely. Api() here produces an instance of the Api class, and is just another object. You can store that in a dictionary, mydict["api"] will retrieve there reference to it just like any other reference. There is no difference between api = Api(), api.testmethod() and mydict = {"api": Api()}, mydict["api"].testmethod() in that respect.
|
|
| Dec 15, 2020 at 14:21 | comment | added | Lo Bellin |
Is it possible to use such a technique with classes? For instance, doing mydict = {'api':Api()} allowing to call Api's methods with mydict['api'].testmethod()? I'm actually considering this, as it would allow me to call the same dictionary key with different underlying classes.
|
|
| May 12, 2014 at 18:36 | history | edited | Martijn Pieters | CC BY-SA 3.0 |
deleted 4 characters in body
|
| Jan 10, 2013 at 22:33 | vote | accept | mdeutschmtl | ||
| Jan 10, 2013 at 22:25 | comment | added | mdeutschmtl | Great top-level explanation, @Martijn, thanks. I think I get the "dispatch" idea. | |
| Jan 10, 2013 at 7:02 | comment | added | Martijn Pieters |
@PhD: Yeah, the example I built is a Command Pattern implementation; the dict acts as the dispatcher (command manager, invoker, etc.).
|
|
| Jan 10, 2013 at 2:03 | comment | added | PhD | @Martjin - Couldn't this be called an implementation of the 'Command Pattern' in that case? Seems like that's the concept the OP is trying to grasp? | |
| Jan 9, 2013 at 20:49 | history | edited | Martijn Pieters | CC BY-SA 3.0 |
added 13 characters in body
|
| Jan 9, 2013 at 20:20 | history | edited | Martijn Pieters | CC BY-SA 3.0 |
added 370 characters in body
|
| Jan 9, 2013 at 20:13 | history | answered | Martijn Pieters | CC BY-SA 3.0 |