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.
-
Should the output be "hello world" or "Hello World!"?Buddy– Buddy2009年06月17日 23:26:37 +00:00Commented Jun 17, 2009 at 23:26
4 Answers 4
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,
stris an unfortunate name for a variable.
1 Comment
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
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
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()