tags:

views:

273

answers:

4

Hola,

Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be)

class helloworld():
    def world(self):
        print "Hello World!"

str = "world"
hello = helloworld()

hello.`str`()

Which would output hello world.

Thanks in advance.

+13  A: 

You can use getattr:

>>> class helloworld:
...     def world(self):
...         print("Hello World!")
... 
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
  • Note that the parens in class helloworld() as in your example are unnecessary, in this case.
  • And, as SilentGhost points out, str is an unfortunate name for a variable.
Stephan202
str is a bad choice for a variable name.
SilentGhost
A: 

one way is you can set variables to be equal to functions just like data

def thing1():
    print "stuff"

def thing2():
    print "other stuff"

avariable = thing1
avariable ()
avariable = thing2
avariable ()

And the output you'l get is

stuff
other stuff

Then you can get more complicated and have

somedictionary["world"] = world
somedictionary["anotherfunction"] = anotherfunction

and so on. If you want to automatically compile a modules methods into the dictionary use dir()

whatsisname
How can you get the output of thing1 by calling blah?
a_m0d
A: 

Warning: exec is a dangerous function to use, study it before using it

You can also use the built-in function "exec":

>>> def foo(): print('foo was called');
...
>>> some_string = 'foo';
>>> exec(some_string + '()');
foo was called
>>>
AgentLiquid
The is really not a good idea. exec should be avoided when possible. getattr is made for this problem.
Stephan202
Don't confuse *how* to do something with whether it's *safe* or not. exec is indeed a dangerous function to use. However, there are ways to use it safely. In this case, you can pass the "globals" and "locals" context dictionaries in order to run exec in a "sandbox".
AgentLiquid
I've heard awful things about exec(), but this worked perfectly.
Vestonian
Keep in mind, Sliggy, that exec is indeed dangerous to use. Make sure you fully understand the weapon before handling it.
AgentLiquid
A: 

What you're looking for is exec

class helloworld():
    def world(self):
        print "Hello World!"

str = "world"
hello = helloworld()

completeString = "hello.%s()" % str

exec(completString)
crackity_jones
that's just plainly wrong
SilentGhost
I have never used "exec" before but I think I'll reconsider... Up-modding.
Peter Ericson