convert a string to a method call ?

Emile van Sebille emile at fenx.com
Thu Nov 15 17:36:12 CET 2001


"Bruce Edge" <bedge at troikanetworks.com> wrote in message
news:25SI7.32$Qh1.10549 at newsfeed.slurp.net...
> I have an object, say xObj, which has a bunch of methods.
> I have the method I want to call in a string, say str.
>
> How do I call method str on xObj?
>
> Use eval? If so, the syntax eludes me.
>

Here's one way:

>>> class Test:
...     def meth1(self, *args):
...             return "meth1: %s" % repr(args)
...     def meth2(self, *args):
...             return "meth2: %s" % repr(args)
...
>>> t = Test()
>>> apply(getattr(t, 'meth1'), (1,2,3))
'meth1: (1, 2, 3)'
>>> apply(getattr(t, 'meth2'), ('a','b','c'))
"meth2: ('a', 'b', 'c')"
>>>

--

Emile van Sebille
emile at fenx.com




More information about the Python-list mailing list