python - Python 中的增量函数名称

标签 python string

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

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

关于python - Python 中的增量函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755690/

相关文章:

java - 为什么Java中字符串变量的声明是大写的?

c# - Object.ReferenceEquals 为匹配的字符串返回 true

c - 是否有在转义模式下打印字符串的功能?

python - 为什么我的 Pygame 窗口只显示几秒钟?

python - 是否可以在 Scipy 的 Mann-Whitney U 检验中指定替代假设?

python - subprocess.check_output() 没有输出

regex - 当某些术语之间可能没有空格时,如何拆分文本行中的项目?

python - 使用其他模型的对象过滤对象

javascript - 未捕获的语法错误 : Unexpected token & in javascript django app

string - 寻找改进我的刽子手代码的方法