如何在Python中测试此功能... TypeError:对象不可调用

时间:2019-02-07 14:15:30

标签: python jupyter-notebook

无法使用3个参数测试函数slowest_call

这是我的学习练习之一。首先,我定义了time_call函数,然后尝试将其用作另一个函数slowest_call的输入。

也许我的输入不太正确(我可以把什么作为第四输入?!)。不知道还有什么尝试。

from time import sleep
from time import time
t = time()
sleep(duration)


 """Return the amount of time the given function takes (in seconds) when called with the given argument """

def time_call(fn, arg):
    t0 = time()
    fn(arg)
    t1 = time()
    elapsed = t1 - t0
    return elapsed
time_call(sleep, 4)  # testing it, it works

 """"Return the amount of time taken by the slowest of the following function
    calls: fn(arg1), fn(arg2), fn(arg3) """

def slowest_call(fn, arg1, arg2, arg3):
return max(time_call(fn, arg1), time_call(fn, arg2), time_call(fn, arg3))

我正在这样测试

slowest_call(time_call(sleep,5), time_call(sleep,3), time_call(sleep,2))

TypeError: slowest_call() missing 1 required positional argument: 'arg3'

它给了我错误,它应该产生最长的时间作为答案(5 ...)。

1 个答案:

答案 0 :(得分:1)

但这根本不是您的slowest_call函数所期望的调用方式。它需要可调用函数本身,然后要使用三个参数来调用它。并且它会为您呼叫time_call。所以:

slowest_call(sleep, 5, 3, 2)