我有一个通用函数,它定义了我计划使用 scipy.integrate.odeint
集成的 ODE 形式,例如:
def my_ode(K, tau, y, u):
return K*u/tau - y/tau # dydt
我的代码中有几个对象,它们都具有 my_ode
中定义的形式的动态,但具有独特的参数 K
和 tau
。我希望能够将一个唯一的句柄传递给 my_ode
,并且在我初始化我的对象时已经设置了这些参数,这样当我更新我的对象时,我所要做的就是 soln = odeint(my_ode, t, y, u)
一些模拟时间 t
。
例如,如果我定义一个类:
class MyThing:
def __init__(self, ode, y0):
# I would rather not maintain K and tau in the objects, I just want the ODE with unique parameters here.
self.ode = ode
self.y = y0
self.time = 0.0
def update(self, t, u):
# I want this to look something like:
self.y = scipy.integrate.odeint(self.ode, t, self.y, u)
当我初始化 MyThing
的实例时,我可以用 Lambdas 做些什么来基本上在初始化时分配参数 K
和 tau
并且永远不需要传递又是他们?我有点卡住了。
最佳答案
如果你有:
def my_ode(K, tau, y, u):
return K*u/tau - y/tau
你可以这样定义:
def make_ode_helper(k, tau):
return lambda (y, u): my_ode(K, tau, y, u)
并且应该能够通过以下方式初始化 MyThing:
mt = new MyThing(make_ode_helper(k, tau), y0)
然后你可以只用 y 和 u 参数调用这个助手:
someresult = ode_helper(y, u)
关于python - 在 Python 中传递参数化函数句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34796953/