首页 > 解决方案 > 需要一些帮助来理解作为函数的参数

问题描述

def question6(f,x,y,z):
    fx=f(x)
    fy=f(y)
    fz=f(z)
    if fx==fy :
       if fy==fz :
          print("Applying f to all three values gives the same result")
          return 1
       else :
          print("Applying f to x and y gives the same result")
          return 2
    elif fx==fz :
       print("Applying f to x and z gives the same result")
       return 3
    elif fy==fz :
       print("Applying f to y and z gives the same result")
       return 4 
    else :
       print("Applying f to each of the three values gives a
              different result")
       return 5 

这段代码已经显示在参数 f 作为函数传递的地方。在代码中 f = f(x),但是 f(x) 是如何工作的并不意味着任何事情或做任何事情

标签: python

解决方案


f(x)f意思是“调用函数x作为参数”。如果f是一个不做任何事情的函数,那么就什么f(x)也不做。如果f是一个做某事的函数,那么f(x)将对x.

这是一个它实际上会做某事的例子:

from typing import Callable

def do_four_times(f: Callable[[int], None]) -> None:
    for x in [1, 2, 3, 4]:
        f(x)

def print_double(i: int) -> None:
    print(i * 2)

do_four_times(print_double)
print("Who do we appreciate?")

推荐阅读