Can Python do this?
Andreas Kostyrka
andreas at mtg.co.at
Mon Mar 4 13:48:27 EST 2002
On Mon, 4 Mar 2002 12:51:13 -0500
"Robert Oschler" <Oschler at earthlink.net> wrote:
> Hello, Python newbie here.
>
> Let's say I'd like to build a method name into a string variable (e.g.
> "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that
> method by somehow having the interpreter evaluate the string variable into a
> call to the desired method? (I know this is usually done in a language like
> Prolog or Lisp but I'm hoping Python can do it too.)
>
> If so, can you point me to a good article or example of such that would show
> me the relevant Python syntax.
Well, in Python your functions/methods are objects also ;)
So the only tricky thing is to get the right dictionary where your objects are stored in:
def func1():
print "func1"
def func2():
print "func2"
def func3():
print "func3"
for x in xrange(1,4):
globals()["func"+str(x)]()
# for object methods this would be something like:
# getattr(obj,"method"+str(x))()
Hope this helps,
Andreas
More information about the Python-list
mailing list