簡體   English   中英

調用 Python function 作為參數傳遞而不知道它是否需要任何參數

[英]Call Python function passed as parameter without knowing if it takes any parameters

我有一個項目,我需要在其中做一些事情,調用幾個函數之一,然后做一些其他事情:

def doCommand(function, parameter_for_function):
  # do a thing
  function(parameter_for_function)
  # do a thing

我的問題是我不知道我將要傳遞的 function 是否需要它自己的參數!

如何讓我的 function 調用沒有參數的函數和有參數的函數?

處理這個問題的首選方法可能是這樣的:

def doCommand(function, *args, **kwargs):
  # do a thing
  function(*args, **kwargs)
  # do a thing

*args**kwargs允許將任意 arguments 傳遞給方法。 顧名思義,這些允許您使用任意數量的 arguments 和關鍵字 arguments 調用doCommand以及傳遞到function

我建議明確地說您使用的 function 是不帶參數調用的:

from typing import Callable

def doCommand(function: Callable[[], None]) -> None:
    # do a thing
    function()
    # do a thing

如果 function 需要參數,則doCommand調用者明確負責提供它們,例如在lambda表達式中:

def foo(param) -> None:
    print("foo: ", param)

doCommand(lambda: foo("bar"))

或命名的包裝器 function:

def foobar() -> None:
    foo("bar")

doCommand(foobar)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM