Skip to main content
 首页 » 编程设计

python之Python 中的增量函数名称

2025年05月04日9duanxz

如果我的问题已经有了答案,我深表歉意,我已经搜索了一段时间的堆栈溢出,但没有找到我可以使用的东西。

我目前正在学习如何创建类,并且我已经为显式 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() 

但是,我意识到必须有更简单的方法来做到这一点。所以我想我可以使用循环和 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() 

但显然这行不通。有谁知道我应该如何处理这个问题?

感谢您的帮助。

请您参考如下方法:

您可以简单地将 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() 

如果你愿意,你可以提前绑定(bind)最后一个参数:

import functools 
solve_Legendre_1 = functools.partial(solve_Legendre, RK=RK_1) 
solve_Legendre_2 = functools.partial(solve_Legendre, RK=RK_2) 
...