我很抱歉,如果已经有我的问题的答案,我已经搜索了堆栈溢出一段时间,但没有发现我可以使用的任何东西.
我正在学习如何创建类,我已经为显式Runge-Kutta方法1-4构建了类.类的名称是'RK_1','RK_2','RK_3'和'RK_4'.为了测试我的代码,我决定解决Legendre微分方程,我还创建了一个叫做"Legendre"的类.
现在我想解决这个问题,所以我写了一个使用特定RK方案的函数并解决了勒让德问题.我想为我的每一个RK方案做这个,所以我写了4次相同的函数,即
def solve_Legendre_1(p,Tmax,init,dt=0.001):
f = Legendre(p)
solver = RK_1(init,f)
while solver.now() < Tmax:
solver(dt)
return solver.state()
def solve_Legendre_2(p,Tmax,init,dt=0.001):
f = Legendre(p)
solver = RK_2(init,f)
while solver.now() < Tmax:
solver(dt)
return solver.state()
def solve_Legendre_3(p,Tmax,init,dt=0.001):
f = Legendre(p)
solver = RK_3(init,f)
while solver.now() < Tmax:
solver(dt)
return solver.state()
def solve_Legendre_4(p,Tmax,init,dt=0.001):
f = Legendre(p)
solver = RK_4(init,f)
while solver.now() < Tmax:
solver(dt)
return solver.state()
Run Code Online (Sandbox Code Playgroud)
但是,我意识到必须有一种更简单的方法来做到这一点.所以我想我可以使用循环和str.format()来改变函数的名称并让它采用相应的RK方案,类似于
for j in range(4):
def solve_Legendre_%s(p,Tmax,init,dt=0.001) % (j+1):
f = Legendre(p)
solver = RK_%s(init,f) % (j+1)
while solver.now() < Tmax:
solver(dt)
return solver.state()
Run Code Online (Sandbox Code Playgroud)
但显然这不会奏效.有谁知道我应该怎么做?
谢谢你的帮助.
您可以简单地将RK_n()函数作为参数传递,以避免重复其他函数:
def solve_Legendre(p,Tmax,init,dt=0.001, RK=RK_1):
f = Legendre(p)
solver = RK(init,f)
while solver.now() < Tmax:
solver(dt)
return solver.state()
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以提前绑定最后一个参数:
import functools
solve_Legendre_1 = functools.partial(solve_Legendre, RK=RK_1)
solve_Legendre_2 = functools.partial(solve_Legendre, RK=RK_2)
...
Run Code Online (Sandbox Code Playgroud)