7

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.

1
  • Should the output be "hello world" or "Hello World!"? Commented Jun 17, 2009 at 23:26

4 Answers 4

16

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.
Sign up to request clarification or add additional context in comments.

1 Comment

str is a bad choice for a variable name.
2

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
>>>

4 Comments

The is really not a good idea. exec should be avoided when possible. getattr is made for this problem.
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".
I've heard awful things about exec(), but this worked perfectly.
Keep in mind, Sliggy, that exec is indeed dangerous to use. Make sure you fully understand the weapon before handling it.
-3

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)

1 Comment

I have never used "exec" before but I think I'll reconsider... Up-modding.
-3

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()

1 Comment

How can you get the output of thing1 by calling blah?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.