Tim Daneliuk a écrit :
On 8/19/2010 7:23 PM, Steven D'Aprano wrote:
On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote:

Problem:

  Given tuples in the form (key, string), use 'key' to determine what
  string method to apply to the string:
table = {'l': str.lower, 'u': str.upper}
table['u']('hello world')
'HELLO WORLD'


(snip)
>
Yeah ... those old assembler memories never quite fade do they.
I dunno what you might call this.  A Function Dispatch Table
perhaps?

I usually refers to this idiom as "dict-based dispatch". And FWIW, it's in fact (part of...) polymorphic dispatch implemention in Python's object model:

>>> str.__dict__['lower']
<method 'lower' of 'str' objects>
>>> d = dict(l="lower", u="upper")
>>> s = "aHa"
>>> for k, v in d.items():
...     print "%s : %s" % (k, s.__class__.__dict__[v](s))

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to