【问题标题】:Calling a function without all the given arguments [duplicate]调用没有所有给定参数的函数[重复]
【发布时间】:2020-12-01 16:45:42
【问题描述】:

我正在尝试理解以下语法。为什么允许传入小于给定结果的参数?例如,

def fit_curve_custom(f, xdata, ydata, p0=None, sigma=None, **kwargs):
   po, pc = curve_fit(f, xdata, ydata, p0, sigma, **kwargs)

def fit(x, a, b, c):
   return a*exp(b)+c

(po, pun, rac, de) = fit_curve_custom(fit, xsamples, yobserved)

在上面的代码中,fit_curve_custom 有六个参数,但是当稍后调用它时,只传递了三个参数,但它仍然按预期运行?这个语法真的有名字吗?另外,fit 函数有四个参数,但在fit_curve_custom 中调用它时没有传递参数?为什么会这样?

【问题讨论】:

  • 参见标准教程中的More on defining functions
  • 该语法称为具有默认参数的函数。另外,fit_curve_custom 调用fit()函数。
  • @martineau 它不调用 fit 函数是什么意思? fit 函数在fit_curve_custom 函数中传递
  • @tdelaney 链接有帮助,你
  • fit_curve_custom()函数中没有调用传递的fit()函数。

标签: python


【解决方案1】:
fit_curve_custom(fit, xsamples, yobserved)

这是可能的,因为fit_curve_custom的最后两个参数是optional argumentnamed arguments

如果没有通过就会有一个默认值 p0=无,sigma=无

最后一个kwargs是一个关键字参数,它是python约定,允许将命名参数的dict传递给函数,在函数内部可以访问它们kwargs['arg1']

例如:

fit_curve_custom(fit, xsamples, yobserved, p1 = None, sigma = None, arg1 = 'a', arg2 = 'b')

fit_curve_custom(fit, xsamples, yobserved)中,fit这里其实并没有被调用,它是传递给fit_curve_custom函数(函数可以作为常规值传递)并被调用,比如:

def fit_curve_custom(f, xdata, ydata, p0=None, sigma=None, **kwargs):
   calc_res = f(10, 10, 10, 10) #  call f
   po, pc = curve_fit(f, xdata, ydata, p0, sigma, **kwargs) #  f is passed to another function

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多