简体   繁体   English

如何定义一个函数以返回两个函数的和?

[英]How do you define a function to return the sum of two functions?

I am working on a Python lesson about functions. 我正在学习有关函数的Python课程。 I created a simple square root function: 我创建了一个简单的平方根函数:

def sqrt(x):
     return x ** 0.5

print(sqrt(9))

Now, I wanted to create a function which can call sqrt (as a parameter) twice: 现在,我想创建一个可以两次调用sqrt (作为参数)的函数:

def add_function(func, x):
    return((func, x) + (func, x))

    print(add_function(sqrt, 9))

However, this gets a syntax error. 但是,这会出现语法错误。 In my mind, the add_function should return the sqrt function with the argument 9 added to the same. 在我看来, add_function应该返回带有参数9的sqrt函数。

I am looking for a some enlightenment. 我正在寻找一些启示。

I suspect this is what you want: use the func variable to call whatever function is passed in. 我怀疑这就是您想要的:使用func变量调用传入的任何函数。

def sqrt(x):
     return x ** 0.5

def add_function(func, x):
    return func(x) + func(x)

print(sqrt(9))
print(add_function(sqrt, 9))

Output: 输出:

3.0
6.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM