考虑一下:
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() 的(默认)返回值,它使用参数 “被调用”。你可以使用 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")
