gpt4 book ai didi

python - 如何编写带有要在以后的代码中定义的变量的函数

转载 作者:行者123 更新时间:2023-12-03 23:20:06 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I write a function that returns another function?

(5 个回答)


去年关闭。




我正在 python3 上创建一个函数来解决 ax^2+bx+c 所以一个二次方程
我的代码如下所示:

def quadratic(a, b, c):
return a*x**2 + b*x + c
但它不会让我这样做,因为 x 未定义。我想在测试代码上使用参数 x
看起来像这样:
def testQuadratic(a, b, c, x):
try:
return quadratic(a, b, c)(x)
except TypeError:
return None
谁能告诉我如何解决这个问题?
谢谢!!

最佳答案

您可以利用 Python 支持一流函数的事实,这些函数可以传入其他函数并从其他函数返回。

def make_quadratic(a, b, c):
def f(x):
return a*(x**2) + b*x + c
return f

# You would call the returned function
my_quadratic = make_quadratic(a, b, c)

# You can then call my_quadratic(x) as you would elsewhere

关于python - 如何编写带有要在以后的代码中定义的变量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64074905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com