如何将函数作为参数并调用它?
How can you take a function as a parameter and call it?
我的任务如下:"Write a function named operate that takes as parameters 2 integers named a, b and a function named func which that takes 2 integers as parameters. Also write the functions add
, sub
, mul
, and div
that take 2 integer parameters and perform the operation corresponding to their name and print the result. Calling operate(a, b, func)
should result in a call to func(a, b)
"。我已经完成了前四个部分,但我仍然停留在如何实现 operate
上。到目前为止,这是我的代码:
# this adds two numbers given
def add(a,b):
print (a + b)
# this subtracts two numbers given
def sub(a,b):
print (b - a)
# this multiplies two numbers given
def mul(a,b):
print (a * b)
# this divides two numbers given
def div(a,b):
print (a / b)
要实现这一点,您需要 return
从您的函数中获取一些东西,而不仅仅是打印一些东西。这使您可以稍后使用结果。为此,只需使用带有某些表达式的 return
语句:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
我已经更改了您的 sub
操作的顺序,以便更符合减法的一般定义方式。
现在写一个operate
函数其实很容易。您已经获得了两个部分:签名应该是 operate(a, b, func)
并且您应该调用 func(a, b)
。这实际上几乎就是它最终会变成的所有内容 - 你需要做的就是再次 return
它(如果你愿意,你也可以在这里 print
它):
def operate(a, b, func):
return func(a, b)
您现在可以这样做:
print(operate(3, 2, add))
print(operate(3, 2, sub))
print(operate(3, 2, mul))
print(operate(3, 2, div))
这将导致输出:
5
1
6
1.5
在评论中我询问了标准库——你看,所有这些都已经由 Python 实现了。您可以将前四个函数定义替换为:
from operator import add, sub, mul, truediv as div
您只需定义 operate
并进行一些测试。
我的任务如下:"Write a function named operate that takes as parameters 2 integers named a, b and a function named func which that takes 2 integers as parameters. Also write the functions add
, sub
, mul
, and div
that take 2 integer parameters and perform the operation corresponding to their name and print the result. Calling operate(a, b, func)
should result in a call to func(a, b)
"。我已经完成了前四个部分,但我仍然停留在如何实现 operate
上。到目前为止,这是我的代码:
# this adds two numbers given
def add(a,b):
print (a + b)
# this subtracts two numbers given
def sub(a,b):
print (b - a)
# this multiplies two numbers given
def mul(a,b):
print (a * b)
# this divides two numbers given
def div(a,b):
print (a / b)
要实现这一点,您需要 return
从您的函数中获取一些东西,而不仅仅是打印一些东西。这使您可以稍后使用结果。为此,只需使用带有某些表达式的 return
语句:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
我已经更改了您的 sub
操作的顺序,以便更符合减法的一般定义方式。
现在写一个operate
函数其实很容易。您已经获得了两个部分:签名应该是 operate(a, b, func)
并且您应该调用 func(a, b)
。这实际上几乎就是它最终会变成的所有内容 - 你需要做的就是再次 return
它(如果你愿意,你也可以在这里 print
它):
def operate(a, b, func):
return func(a, b)
您现在可以这样做:
print(operate(3, 2, add))
print(operate(3, 2, sub))
print(operate(3, 2, mul))
print(operate(3, 2, div))
这将导致输出:
5
1
6
1.5
在评论中我询问了标准库——你看,所有这些都已经由 Python 实现了。您可以将前四个函数定义替换为:
from operator import add, sub, mul, truediv as div
您只需定义 operate
并进行一些测试。