使用字符串作为变量名
有没有办法让我用一个字符串来调用一个类的方法呢?我这里有个例子,希望能更清楚地说明这个问题(这是我认为应该这样做的方式):
class helloworld():
def world(self):
print "Hello World!"
str = "world"
hello = helloworld()
hello.`str`()
这样的话就会输出 Hello World!
。
提前谢谢你们。
4 个回答
-3
你要找的东西是 exec
class helloworld():
def world(self):
print "Hello World!"
str = "world"
hello = helloworld()
completeString = "hello.%s()" % str
exec(completString)
2
警告:exec是一个很危险的函数,使用之前要好好研究一下
你还可以使用内置的函数“exec”:
>>> def foo(): print('foo was called');
...
>>> some_string = 'foo';
>>> exec(some_string + '()');
foo was called
>>>
16
你可以使用 getattr
:
>>> class helloworld:
... def world(self):
... print("Hello World!")
...
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
- 注意,在你的例子中,
class helloworld()
里的括号其实是多余的。 - 还有,正如 SilentGhost 指出的那样,
str
这个名字用作变量名不太合适。