python – 使用string作为变量名

前端之家收集整理的这篇文章主要介绍了python – 使用string作为变量名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有什么方法可以使用字符串来调用类的方法吗?这是一个有希望更好地解释的例子(使用我认为的方式):
  1. class helloworld():
  2. def world(self):
  3. print "Hello World!"
  4.  
  5. str = "world"
  6. hello = helloworld()
  7.  
  8. hello.`str`()

哪个会输出Hello World!.

提前致谢.

解决方法

你可以使用 getattr
  1. >>> class helloworld:
  2. ... def world(self):
  3. ... print("Hello World!")
  4. ...
  5. >>> m = "world"
  6. >>> hello = helloworld()
  7. >>> getattr(hello,m)()
  8. Hello World!

>请注意,在本例中,类似helloworld()中的parens是不必要的.
>并且,正如SilentGhost指出的那样,str是一个变量的不幸名称.

猜你在找的Python相关文章