Python:partial需要三个参数

时间:2016-05-01 13:00:12

标签: python syntax partial

我正在尝试通过阅读本书Data Science from Scratch by Joel Grus来学习Python,而在第94页,他们描述了如何使用以下代码近似f = x ^ 2的导数

def difference_quotient(f, x, h):
    return (f(x + h) - f(x)) / h

def square(x):
    return x * x

def derivative(x):
    return 2 * x

derivative_estimate = partial(difference_quotient, square, h=0.00001)

# plot to show they're basically the same
import matplotlib.pyplot as plt
x = range(-10,10)
plt.title("Actual Derivatives vs. Estimates")
plt.plot(x, map(derivative, x), 'rx', label='Actual')
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
plt.legend(loc=9)
plt.show()

一切正常,但是当我将行derivative_estimate = partial(difference_quotient, square, h=0.00001)更改为derivative_estimate = partial(difference_quotient, f=square, h=0.00001)时(因为我认为阅读更清楚),我得到以下错误

Traceback (most recent call last):
  File "page_93.py", line 37, in <module>
    plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
TypeError: difference_quotient() got multiple values for keyword argument 'f'

这里发生了什么?

1 个答案:

答案 0 :(得分:7)

本主题回答并完美解释:

在您的情况下暗示您应将x作为关键字参数传递

plt.plot(x, [derivative_estimate(x=item) for item in x], 'b+', label='Estimate')