繁体   English   中英

如何在python中传递带有参数的函数?

[英]How to pass a function with parameters with a function in python?

考虑一下:

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(nestedfunc("is called"), string="not default")


def function2(func, string="default"):
   try:
      #doing some setting
      func()
   finally:
      #reset back to setting

我正进入(状态:

func()
TypeError: 'NoneType' object is not callable

我假设func()没有传递参数,它会导致错误。

为了澄清,期望的结果是能够调用添加了任意数量参数的func()。

有谁知道正确的方法是什么? 任何建议将不胜感激!

您的function2接收到func=None因为那是nestedfunc()的(默认)返​​回值,该返回值使用参数"is called" 您可以使用functools.partial来“冻结”某些函数的参数:

from functools import partial

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(partial(nestedfunc, "is called"), string="not default")

nestedfunc("is called")是函数调用返回的值: None 您应该将nestedfunc传递给function2 而不要先调用它。

如果要将参数传递给nestedfuncnestedfunc将其传递给function2

def function1():
   def nestedfunc(param1, **kw):
      logging.info("nested function %s" % kw) #error
   function2(nestedfunc, "is called", string="not default")


def function2(func, funcparam, string="default"):
   try:
      #doing some setting
      func(funcparam)
   finally:
      #reset back to setting

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM