如何将变量作为参数传递

时间:2017-05-02 01:47:43

标签: python python-2.7

我有几个函数可以对应用程序进行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())

1 个答案:

答案 0 :(得分:2)

是的,可以将函数与其他对象一起传递。

在您的特定情况下,您已将函数的执行与函数本身混淆。

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