Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string as variable name

Tags:

python

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.

like image 255
Steve Gattuso Avatar asked Jun 17 '09 22:06

Steve Gattuso


2 Answers

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.
like image 65
Stephan202 Avatar answered Oct 14 '22 05:10

Stephan202


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
>>>
like image 37
AgentLiquid Avatar answered Oct 14 '22 03:10

AgentLiquid