Python 如何将变量作为参数传递
我有几个函数可以对应用程序进行API调用。每个函数都设置为返回json格式信息。我声明了另一个函数,将json输出写入一个文件,以便在编码时保存。我在尝试传递函数以使API调用成为参数时遇到问题。这可能吗Python 如何将变量作为参数传递,python,python-2.7,Python,Python 2.7,我有几个函数可以对应用程序进行API调用。每个函数都设置为返回json格式信息。我声明了另一个函数,将json输出写入一个文件,以便在编码时保存。我在尝试传递函数以使API调用成为参数时遇到问题。这可能吗 class ApiCalls(object): def __init__(self, url='https://application.spring.com', username='admin',
class ApiCalls(object):
def __init__(self,
url='https://application.spring.com',
username='admin',
password='pickles',
path='/tmp/test/'):
self.url = url
self.username = username
self.password = password
self.path = path
def writetofile(self, filename, call):
if not os.path.exists(self.path):
os.makedirs(self.path)
os.chdir(self.path)
f = open(self.filename, 'w')
f.write(str(self.call))
f.close()
def activationkey(self):
credentials = "{0}:{1}".format(self.username, self.password)
url = self.url + '/katello/api/organizations/1/activation_keys'
cmd = ['curl', '-s', '-k',
'-u', credentials, url]
return subprocess.check_output(cmd)
x = ApiCalls()
x.writetofile('activationkey.json', activationkey())
是的,可以像其他对象一样传递函数 在您的特殊情况下,您将函数的执行与函数本身混淆了 考虑以下示例中的
square
:
def square(val):
return val * val
您正试图将其作为
def func_of_1(func):
return func # You return the 'function' here
assert func_of_one(square()) == 1 # You call the function here
但你应该这么做
def func_of_1(func):
return func(1) # Call the function with the argument here
assert func_of_one(square) == 1 # Pass the function here
def writetofile(self, filename, call):
...
f.write(str(call()))
...
x.writetofile('activationkey.json', activationkey)
要回答上述非常具体的用例,您应该
def func_of_1(func):
return func(1) # Call the function with the argument here
assert func_of_one(square) == 1 # Pass the function here
def writetofile(self, filename, call):
...
f.write(str(call()))
...
x.writetofile('activationkey.json', activationkey)
你不说你的“问题”是什么,这使得这个问题很难回答。还缺少上下文,我假设
def…(self…
函数是名为ApiCalls
的类的一部分。在我调用filename和call variables的writetofile函数中,call变量就是被调用的函数。这更有意义吗?@SkyVar听起来像是你想简单地对类执行filename(self)
和call(self)
Thx@Cireo,调用时我必须使用class对象来调用函数,所以看起来像这样:def writetofile(self,filename,call):如果不是os.path.exists(self.path):os.makedirs(self.path)os.chdir(self.path)f=open(filename,'w')f.write(call())f.close()x.writetofile('activationkey.json',x.activationkey)很抱歉,我想不出如何使它看起来像注释中的代码……我失败了是的,对于您需要使用的类,x.activationkey
,因为将不再定义activationkey
。我不相信您可以在注释中使用块代码,不要担心=)