加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用string作为变量名

发布时间:2020-12-16 23:36:37 所属栏目:Python 来源:网络整理
导读:我有什么方法可以使用字符串来调用类的方法吗?这是一个有希望更好地解释的例子(使用我认为的方式): class helloworld(): def world(self): print "Hello World!"str = "world"hello = helloworld()hello.`str`() 哪个会输出Hello World!. 提前致谢. 解决
我有什么方法可以使用字符串来调用类的方法吗?这是一个有希望更好地解释的例子(使用我认为的方式):
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是一个变量的不幸名称.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读