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.
You can use getattr
:
>>> class helloworld:
... def world(self):
... print("Hello World!")
...
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
class helloworld()
as in your example are unnecessary, in this case.str
is an unfortunate name for a variable.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
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With