Method by name lookup
will.hartung at havasint.com
Sat Nov 4 01:09:20 CET 2000
Alex Martelli wrote in message <8tsu1v015s at news2.newsguy.com>...
>"Will Hartung" <will.hartung at havasint.com> wrote in message
>news:8tsboe0rcs at news1.newsguy.com...
>> I can't use something like:
>> funcitem = instance.funcname
>> because funcname may not exist in the object.
>While the already-suggested getattr is surely best in this
>case, I just wanted to point out that just because something
>might fail doesn't mean you can attempt it anyway -- often,
>the 'try, but catch a possible exception' attempt comes in
>very useful. So, as a general approach, though certainly
>not optimal here, do remember that, e.g.,...:
> try: funcitem = instance.funcname
> except AttributeError: funcitem = None
>is roughly equivalent to the more concise & specific:
> funcitem = getattr(instance, 'funcname', None)
Yes, of course. But for my case, it's a completely dynamic lookup. I'm
constructing method names based on properties, so, I can't do "funcitem =
But thanx for the tips!
(will.hartung at havasint.com)
More information about the Python-list