Can Python do this?
Paul Rubin
phr-n2002a at nightsong.com
Mon Mar 4 15:41:50 EST 2002
"Robert Oschler" <Oschler at earthlink.net> writes:
> 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.
x = my_class() # x is an instance of some class
method_name = "FuncCall" + "1" # gives "FuncCall1"
method = getattr(x, method_name) # find the method
method (args) # call the method
is preferable to using eval, if method_name is actually defined for
my_class. However, if method_name is only defined for some class that
my_class inherits from, and not from my_class itself, then this won't
work.
Anyone know a way to find a method taking inheritance into account?
More information about the Python-list
mailing list