[英]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
而不要先調用它。
如果要將參數傳遞給nestedfunc
, nestedfunc
將其傳遞給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.