我有什么方法可以使用字符串来调用类的方法吗?这是一个有希望更好地解释的例子(使用我认为的方式):
- class helloworld():
- def world(self):
- print "Hello World!"
- str = "world"
- hello = helloworld()
- hello.`str`()
哪个会输出Hello World!.
提前致谢.
解决方法
你可以使用
getattr
:
- >>> class helloworld:
- ... def world(self):
- ... print("Hello World!")
- ...
- >>> m = "world"
- >>> hello = helloworld()
- >>> getattr(hello,m)()
- Hello World!
>请注意,在本例中,类似helloworld()中的parens是不必要的.
>并且,正如SilentGhost指出的那样,str
是一个变量的不幸名称.