如何将变量作为参数传递

2024-10-02 22:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个函数可以对应用程序进行API调用。每个函数都被设置为返回json格式的信息。我声明了另一个函数来将json输出写入一个文件,以便在编码时保存。我在尝试传递函数以使API调用成为参数时遇到了问题。这有可能吗

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())

Tags: path函数selfapijsonurlosdef
1条回答
网友
1楼 · 发布于 2024-10-02 22:25:09

是的,可以像其他对象一样传递函数

在您的特殊情况下,您混淆了函数的执行和函数本身

考虑下例中的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)

相关问题 更多 >