Using string as variable name

python

Solution

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.

Problem

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.

Original source