【问题标题】:How do you pass a function as an argument to another function, but the initial function's arguments change?如何将一个函数作为参数传递给另一个函数,但初始函数的参数发生变化?
【发布时间】:2022-11-12 19:42:00
【问题描述】:

您如何编写一个函数 f,它接受另一个函数 g 作为参数,但函数 g 的参数会根据函数 f 中发生的情况动态变化?

一个伪代码示例是:

def function(another_function(parameters)):  # another function passed as an argument, with parameters
    for i in range(10):
        print(another_function(i))

所以当 i 迭代时,函数 f 每次都会用一个新的参数 i 被调用。如何实施?

我发现可以使用 *args 作为参数,但没有看到它是如何实现的。

干杯

【问题讨论】:

  • IIUC,您只需将 another_funciton 传递给函数(不带参数)。因此:def function(another_function): ...

标签: python function syntax


【解决方案1】:

让我们创建一个带有两个参数的函数。第一个参数是对函数的引用,另一个是该函数要使用的参数

def func1(func, p):
    func(p)

func1(print, 'Hello world!')

所以我们调用 func1 并引用内置的打印功能(不必是内置的 - 可以是范围内的任何功能)

输出:

Hello world!

【讨论】:

    【解决方案2】:

    你的例子几乎是正确的。你可以简单地写:

    def function(another_function):
        for i in range(10):
            print(another_function(i))
    

    在 Python 中,函数只是对象,就像数字、字符串和列表一样,因此不需要像这样使用特殊语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 2019-10-09
      • 2013-04-13
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      相关资源
      最近更新 更多