Method call from string

ZnU znu at znu.dhs.org
Fri Jun 7 02:08:14 EDT 2002


In article <3D004DB1.62BEB68A at engcorp.com>,
 Peter Hansen <peter at engcorp.com> wrote:

> ZnU wrote:
> > 
> > Say I've got a variable with the value 'do_something', and I have an an
> > object that happens to have a do_something method. How can I call that
> > method based on the value of the variable? Preferably without using
> > eval() or similar.
> 
> >>> var = 'do_something'
> >>> class A:
> ...   def do_something(self):
> ...      print 'ooga booga'
> ...
> >>> a = A()
> >>> getattr(a, var)
> <bound method A.do_something of <__main__.A instance at 0x007B0110>>
> >>> f = getattr(a, var)
> >>> f()
> ooga booga

Now that I actually think things though, that makes perfect sense. I 
should have been able to figure that one out myself. Thanks.

-- 
Right now the Internet gives an awfully good imitation of providing superhuman
intelligence capability, both in terms of the total hardware that is out there
and the fact that the 'net has all these human-equivalent peripheral devices
called "users" that can be appropriated in a distributed way to attack problems.
                    --Vernor Vinge



More information about the Python-list mailing list