python class中的方法调用

代码如下

class AutoGetSoftware():

    def __init__(self):
        self.headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Cache-Control': 'max-age=0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Connection': 'keep-alive',
            'Referer': 'http://www.baidu.com/'
        }
        
    def get_nginx(self):
       print(nginx)

    def get_tomcat(self):
       print(tomcat)

    def get_mysql(self):
        print(mysql)

有没有什么办法可以通过变量来执行里面的方法

类似这样

    main = AutoGetSoftware()
    for i in ["nginx","tomcat","mysql"]:
        methods = "get_%s" % i
        # 伪代码无法执行
        main.methods()
阅读 1.9k
2 个回答
name = "get_%s()" % i
method = getattr(main, name)
if callable(method):
    method()
class AutoGetSoftware(object):

    def __init__(self):
        self.headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Accept-Encoding': 'gzip, deflate, br',
            'Cache-Control': 'max-age=0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Connection': 'keep-alive',
            'Referer': 'http://www.baidu.com/'
        }

    def get_nginx(self):
        print('nginx')

    def get_tomcat(self):
        print('tomcat')

    def get_mysql(self):
        print('mysql')


main = AutoGetSoftware()
for i in ["nginx", "tomcat", "mysql"]:
    methods = "get_%s()" % i
    # 伪代码无法执行
    # main.methods()
    eval('main.' + methods)

用eval(),不知道你是不是这个意思?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题