python class中的方法调用

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)

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

类似这样

python">    main = AutoGetSoftware()

for i in ["nginx","tomcat","mysql"]:

methods = "get_%s" % i

# 伪代码无法执行

main.methods()


回答:

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(),不知道你是不是这个意思?

以上是 python class中的方法调用 的全部内容, 来源链接: utcz.com/a/38466.html

回到顶部