Python scipy.integrate.romberg——如何传递带有关键字参数的函数

Python scipy.integrate.romberg——如何传递带有关键字参数的函数,python,scipy,numerical-integration,Python,Scipy,Numerical Integration,希望这是一个快速、简单的问题,但它让我有点困惑 我有一个函数,它接受两个强制参数和几个我想使用scipy.integrate.romberg集成的关键字参数。我知道我可以使用args关键字将额外参数传递给scipy.integrate.romberg,在这里我可以将额外参数指定为元组,但是,在元组中,我如何指定哪个函数参数是关键字参数,哪些是关键字参数 e、 g 起初,我尝试在类中定义函数,以便在_init__中设置所有关键字参数,但是scipy.integrate.romberg似乎不喜欢我传

希望这是一个快速、简单的问题,但它让我有点困惑

我有一个函数,它接受两个强制参数和几个我想使用scipy.integrate.romberg集成的关键字参数。我知道我可以使用args关键字将额外参数传递给scipy.integrate.romberg,在这里我可以将额外参数指定为元组,但是,在元组中,我如何指定哪个函数参数是关键字参数,哪些是关键字参数

e、 g

起初,我尝试在类中定义函数,以便在_init__中设置所有关键字参数,但是scipy.integrate.romberg似乎不喜欢我传递一个以self作为第一个参数的函数。恐怕现在没有错误信息

有什么想法吗


谢谢

原始帖子的注释建议将关键字参数作为位置参数传递。这是可行的,但是如果有许多关键字参数,并且您不想显式地传递它们,那么这将非常麻烦。一种更通用、或许更具python风格的方法是使用如下闭包来包装函数:

def myfunc(x,y,a=1,b=2):
    if y > 1.0:
         c = (1.0+b)**a
    else:
         c = (1.0+a)**b
    return c*x

def mywrapper(*args, **kwargs):
    def func(x):
        return myfunc(x, *args, **kwargs)
    return func

myfunc_with_args = mywrapper(2.5, a=4.0, b=5.0)
integral = integrate.romberg(myfunc_with_args, 1, 10)

你有没有试过做rombergmyfunc,1,10,2.5,?它通过位置知道哪个论点是哪个论点的方式。参数从第一个传递到最后一个。您提到了关键字参数,但我看不出它们之间有什么密切关系,因为您的关键字参数有默认值,并且您没有传递任何值来覆盖这些默认值。@BrenBarn:应该可以,但函数有四个参数,在问题中显示的代码中,OP有a=4.0和b=5.0,因此调用应该是rombergmyfunc,1,10,args=2.5,4.0,5.0。显式关键字args不是必需的,这只是我个人的偏好。啊,好吧,那么我可以按照参数在函数声明中出现的顺序来指定参数?我猜如果我上面的示例代码本身在另一个函数中,并且我使用**kwargs传递关键字参数,那么我必须依次遍历并提取每个参数,然后放入元组中?
def myfunc(x,y,a=1,b=2):
    if y > 1.0:
         c = (1.0+b)**a
    else:
         c = (1.0+a)**b
    return c*x

def mywrapper(*args, **kwargs):
    def func(x):
        return myfunc(x, *args, **kwargs)
    return func

myfunc_with_args = mywrapper(2.5, a=4.0, b=5.0)
integral = integrate.romberg(myfunc_with_args, 1, 10)