Given a string - execute a function by the same name
John Schroeder
jschroed at gmail.com
Thu May 8 12:48:15 EDT 2008
You can do it with a class using the __getattr__ function. There might be a
way to do it without a class but I don't how to do it that way.
class AllMyFunctions(object):
def a(self):
print "Hello. I am a."
def b(self):
print "Hey. I'm b."
x = raw_input("Enter a function to call: ")
if x not in AllMyFunctions().__dict__:
print "That's not a function that I have."
else:
getattr(AllMyFunctions(), x)()
On Thu, May 8, 2008 at 9:33 AM, Andrew Koenig <ark at acm.org> wrote:
> <python at bdurham.com> wrote in message
> news:mailman.291.1209400412.12834.python-list at python.org...
>
> > I'm parsing a simple file and given a line's keyword, would like to call
> > the equivalently named function.
>
> No, actually, you woudn't :-) Doing so means that if your programs input
> specification ever changes, you have to rename all of the relevant
> functions. Moreover, it leaves open the possibility that you might wind up
> calling a function you didn't intend.
>
> The right way to solve this kind of problem is to list all the functions
> you
> wish to be able to call in this way, and then explicitly define a mapping
> from keywords to the appropriate functions. Which is exactly what you're
> doing in
>
> > 3. Place all my functions in dictionary and lookup the function to be
> > called
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080508/cbffe04b/attachment-0001.html>
More information about the Python-list
mailing list