【问题标题】:send arguments for function arguments in python在python中发送函数参数的参数
【发布时间】:2014-01-19 15:53:09
【问题描述】:

我有一个函数,它接收一个函数参数,该函数参数也接收一个参数,但我不知道如何将此参数传递给 python 中的参数函数。这是示例代码:

def pr(text):
   print(text)

def frun(func):
   func()

frun(pr)

问题是如何在frun(pr) 中传递text 参数? 并且请考虑使用关键字参数。

【问题讨论】:

    标签: python arguments function-pointers


    【解决方案1】:

    如果你只有一个论点,你可以这样做:

    def pr(text):
       print(text)
    
    def frun(func, text):
       func(text)
    
    frun(pr, "blah")
    

    否则,您可以使用可变参数“魔术”,例如:

    def pr(text):
       print(text)
    
    def frun(func, *args):
       func(*args)
    
    frun(pr, "blah")
    

    后者的可读性要差得多,并且可能导致奇怪的错误(在这种情况下,它甚至无法使用多个传递的参数,因为pr 只需要一个位置参数),有时仍然是必要的。例如,当您先验不知道您的函数需要多少参数时:

    def pr1(text):
        print(text)
    
    def pr2(text, note):
        print(text, note)
    
    def frun(func, *args):
       func(*args)
    
    frun(pr1, "foobarbaz")
    frun(pr2, "blah", "IT WORKS!")
    

    【讨论】:

    • 谢谢,但你的回答在关键论点上不好,有些方法不起作用。
    【解决方案2】:

    TL;DR: Partial Application

    问题归结为将func 的参数传递给您要在其中进行评估的范围。有几种方法可以做到这一点。

    显式参数化

    如果你有很多函数,或者很深的函数调用树,这个 get 就很笨拙。

    def pr(text):
      print(text)
    
    def frun(func, *func_args):
      func(*func_args)
    
    frun(pr, *pr_args)
    

    Deferred Execution with Lambda

    限制:在创建lambda 时,您需要同时提供func 的所有参数。

    def pr(text):
      print(text)
    
    def frun(func):
      func()
    
    frun(lambda: pr(*pr_args))
    

    Partial Application

    这里的好处是您可以在传递对象时执行部分应用程序。如果您partial 使用命名变量,那么您就消除了参数的排序问题。

    from functools import partial
    
    def pr(text):
      print(text)
    
    def frun(func):
      func()
    
    frun(partial(pr, *pr_args))
    

    【讨论】:

      【解决方案3】:

      您可以使用lambda 函数将pr 函数连同参数一起传递给frun 函数,而无需更改您的代码。

      def pr(text):
          print(text)
      
      # just another example to show how to pass more than one argument.
      def pr2(text, note):
          print(text, note)
      
      
      def frun(func):
          func()
      
      
      frun(lambda: pr('Hello'))
      frun(lambda: pr2('Hello', 'World'))
      
      Hello
      Hello World
      

      另一种可能对您有用的方法是将funcfrun 中作为callback 函数返回, 然后用参数调用它:

      def pr(text):
          print(text)
      
      # just another example to show how to pass more than one argument.
      def pr2(text, note):
          print(text, note)
      
      
      def frun(func):
          # do some stuff
          return func
      
      
      frun(pr)('Hello')
      frun(pr2)('Hello', 'World')
      
      
      Hello
      Hello World
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        相关资源
        最近更新 更多