python – 使用string作为变量名

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

哪个会输出Hello World!.

提前致谢.

解决方法

你可以使用 getattr: @H_404_2@>>> class helloworld: ... def world(self): ... print("Hello World!") ... >>> m = "world" >>> hello = helloworld() >>> getattr(hello,m)() Hello World!

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

猜你在找的Python相关文章