Python 将函数压缩成字符串

Python Compact function into String

我有这样的功能:

def ease_bounce_out(t, bounces=None):
    if bounces is None:
        bounces = [4 / 11, 6 / 11, 8 / 11, 3 / 4, 9 / 11, 10 / 11, 15 / 16, 21 / 22, 63 / 64]

    bounces.insert(0, 1 / bounces[0] / bounces[0])
    if t < bounces[1]:
        return bounces[0] * t * t
    else:
        for i in range(3, len(bounces) - 2, 3):
            if t < bounces[i]:
                t -= bounces[i - 1]
                return bounces[0] * t * t + bounces[i + 1]

    t -= bounces[len(bounces) - 2]
    return bounces[0] * t * t + bounces[len(bounces) - 1]

我想将它全部压缩成 1 个字符串,这样我就可以使用 eval() 函数来获取 t 的任何值的输出。我有一个更简单的函数的例子:

def ease_poly(t, power=2):
    t *= 2
    if t < 1:
        return t ** power
    else:
        return 2 - ((2 - t) ** power)

会变成:

def ease_poly(power=2):
    return f"(t * 2) ** {power} if (t * 2) < 1 else 2 - ((2 - (t * 2)) ** {power})"

这样,我可以使用这个字符串并通过简单地执行以下操作来计算 t 的任何值的函数:

ease = ease_poly(power=3)
t = 0.4  # 0 <= t <= 1
print(eval(ease)) 

现在开始回答我的问题,它实际上不必是 1 行,这就是我一直在想的:

def ease_bounce_out(bounces=None):
    if bounces is None:
        bounces = [4 / 11, 6 / 11, 8 / 11, 3 / 4, 9 / 11, 10 / 11, 15 / 16, 21 / 22, 63 / 64]

    return # some code here that compiles the rest into a string

一个小提示,

  1. 反弹[-1] = 最后一项

    反弹[-2] = 最后第二个项目

    不要使用反弹[len(bounces) - 1]

回答: 你不能用 eval 得到那个字符串答案。因为 你的函数是根据 t 做出决定的。你必须通过 t.

如果对所有 t 进行评估是您最关心的问题,那么其他方法可能会有所帮助。忘记评估。 不要传递 t 但在函数中使用 t 然后它将在全局范围内查找并在该范围内使用 t。

示例:

此函数需要传递t。

def mathuer(t, b = 23 ):
    x = t
    if b > t:
        x = t
    return x

此函数使用全局 t。

def mathuer(b = 23 ):
    x = t
    if b > t:
        x = t
    return x

这就是它的工作原理,

t = 34
obj = mathuer() // Uses t defined above