Is this considered black magic?
Christian Tanzer
tanzer at swing.co.at
Mon Nov 12 03:34:41 EST 2001
Laura Creighton <lac at strakt.com> wrote:
> I want to do something which is conceptually very simple. Given a list of
> objects, call make everybody call the same method you want to run. Sort
> of like apply(), but for methods.
>
> This is what I came up with:
(snip)
> def foreach(name_key, object_list, *args):
> print 'foreach: args are ' + `args`
> for object in object_list:
> try:
> object.__class__.__dict__[name_key](object, *args)
> except KeyError:
> pass
Hi Laura,
Using `__class__.__dict__` to access the method means that neither
inherited methods nor methods in the instance dictionary are handled
correctly.
`getattr` is the better choice (and less magic).
I'd also add `** kw` to the function.
Christian
--
Christian Tanzer tanzer at swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92
More information about the Python-list
mailing list