函数可以是函数定义的参数吗

当我们定义我们的自定义函数时,我们可以添加另一个函数作为我们的参数之一。我在这个问题上徘徊,并没有得到这背后的概念。

以下是一些让我感到困惑的例子。

def func1(x,y=len()): 
   pass

我想知道当我们调用它们时这些函数参数会发生什么

我很感激如果有人能指出用另一个函数作为参数来实现一个函数的所有方法。


慕后森
浏览 218回答 2
2回答

慕尼黑5688855

函数是像其他任何东西一样的对象。一旦你定义了一个>>> def foo(param):...&nbsp; &nbsp; &nbsp;return "Do all the " + param...&nbsp;您可以将它传递给另一个函数并让该函数进行调用>>> def bar_1(func, param):...&nbsp; &nbsp; &nbsp;print(func(param))...&nbsp;>>> bar_1(foo, "things")Do all the things您可以使用函数对象作为默认参数>>> def bar_2(func=foo, param=""):...&nbsp; &nbsp; &nbsp;print(func(param))...&nbsp;>>> bar_2()Do all the&nbsp;您甚至可以调用函数并使用其结果来设置参数的默认值>>> def bar_3(text=foo("things")):...&nbsp; &nbsp; &nbsp;print(text)...&nbsp;>>> bar_3()Do all the things但是您不能调用函数来定义参数名称本身。在这里,您似乎希望len()(返回 int 或在这种情况下失败)的结果是参数的名称,但这违反了 python 的语法规则。>>> def func1(x,y,len()):&nbsp; File "<stdin>", line 1&nbsp; &nbsp; def func1(x,y,len()):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^SyntaxError: invalid syntax

白衣非少年

您的代码示例都有语法错误,因此不清楚您到底在追求什么。但是,是的,您可以将一个函数作为参数传递给另一个函数。常见的示例是回调函数或您可能希望在另一个过程中应用的函数。这是一个例子:# print_os takes an integer and prints that many o'sdef print_os(n):&nbsp; &nbsp; print('o' * n)# here, f is expected to be a function, any function that takes an integerdef for_multiples_of_three(xs, f):&nbsp; &nbsp; for x in xs:&nbsp; &nbsp; &nbsp; &nbsp; if x % 3 == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f(x)for_multiples_of_three([2, 6, 1, 9, 4, 5, 3], print_os)结果:oooooooooooooooooo或这个:def first_letter(s):&nbsp; &nbsp; return s[0] if s else ''def for_each_word(s, f):&nbsp; &nbsp; return [f(x) for x in s.split()]print(for_each_word('Not a very useful function', first_letter))结果:['N', 'a', 'v', 'u', 'f']需要注意的重要一点是,函数只是您可以在 Python 中执行的另一件事。类似于将数字、字符串或其他对象分配给变量以便以后能够使用它,您可以将函数分配给变量并稍后调用它。您的示例中的错误是您添加了(),这意味着 Python 尝试调用该函数并从中获取结果 - 然后将结果传递给下一个函数。那不是用函数调用函数,而是用另一个函数的结果调用函数:def three():&nbsp; &nbsp; return 3def print_sum(x, y):&nbsp; &nbsp; print(x+y)print_sum(2, three())结果:5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python