Python:partial需要三个参数

Hun*_*ter 4 python syntax partial

我正在尝试通过阅读Joel Grus撰写的" Scratch数据科学 "一书来学习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()
Run Code Online (Sandbox Code Playgroud)

一切工作正常,但是当我改线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'
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

ale*_*cxe 7

在本主题中回答并完美解释:

在您的情况下,这意味着您应该x作为关键字参数传递:

plt.plot(x, [derivative_estimate(x=item) for item in x], 'b+', label='Estimate')
Run Code Online (Sandbox Code Playgroud)