[英]Master function that executes subfunctions
我有兩個接受不同參數的函數:
def foo(name, age):
pass
def bar(color, shape):
pass
現在,我有一個主函數,我希望能夠使用我要執行的函數及其參數進行調用。 由於它是一個可以調用foo或bar的主函數,因此僅使用兩個參數(要執行的函數和該函數的參數)進行調用。
function是一個字符串,告訴執行什么功能
params將是參數字典(例如** kwargs)
我可以這樣做以使其工作:
def master(function, params):
if function == 'foo':
foo(params['name'], params['age'])
elif function == 'bar':
foo(params['color'], params['shape'])
然后我打電話給師父:
master('foo',{'name': 'John', 'age': 99})
但是,如果master需要調用許多子功能,則條件太多,無法為每個函數選擇正確的參數。
所以我基本上有兩個問題:
1)我可以直接傳遞要執行的功能,而不是用功能名稱調用master,然后在某種情況下檢查該名稱嗎? 如果是這樣,我該如何執行該功能?
像這樣打電話給主人:
master(foo(), {'name': 'John', 'age': 99})
2)函數foo
和bar
沒有** kwargs,但是如果我可以僅通過字典調用它們,然后將它們從dict分配給每個變量,這將非常方便。
所以基本上,我可以這樣做:
params = {'name':'John', 'age':99, 'color':red, 'shape':circle}
foo(params) # I would like to to this even if foo doesn't have **kwargs
bar(params) # same for bar
因此,最后,我理想的主人呼吁是:
params = {'name':'John', 'age':99, 'color':red, 'shape':circle}
master(foo(), params) # to execute foo
master(bar(), params) # to execute bar
您可以將函數作為參數傳遞:
def master(func, arguments: dict):
if func is foo:
args = arguments["name"], arguments["age"]
elif func is bar:
args = arguments["color"], arguments["shape"]
return func(*args)
如果您不知道函數參數的名稱,則可以更簡單地完成此操作:
def master(func, arguments: list):
return func(*arguments)
以下是更為通用的版本:
def master(function, *positional_arguments, **keyword_arguments):
function(*positional_arguments, **keyword_arguments)
master(foo, 'John', 56)
master(foo, **{'name': 'John', 'age': 56})
master(foo, name='John', age=56)
master(foo, *['John', 56])
函數是Python中的一類對象 ,因此可以分配給標識符,作為參數傳遞或由函數返回。
您不想為特定功能打擾關鍵字args的統一方法-具有inspect.getfullargspec
功能:
import inspect
def foo(name, age):
print(name, age)
def bar(color, shape):
print(color, shape)
def master(func, params):
arg_names = inspect.getfullargspec(func).args
func(**{k:v for k,v in params.items() if k in arg_names})
params = {'name':'John', 'age':99, 'color':'red', 'shape':'circle'}
master(foo, params)
master(bar, params)
樣本輸出:
John 99
red circle
python中的函數是對象,因此可以,您可以將它們作為參數傳遞(但不要使用括號)。
def master(function, **kwargs):
function(params, kwargs)
然后,您致電主人:
master(foo, name='John', age=99...)
您可以通過master函數執行函數,而不是通過在master內部傳遞函數作為參數,而是通過傳遞函數定義來執行。 請遵循以下示例:
def foo(name, age):
pass
def bar(color, shape):
pass
現在考慮一個主函數:
Func參數將通過在函數名稱后添加括號來包含函數的定義,使其執行。
def masterFunc(func, params):
return func(params) # Func param will contain the defination of the function by adding parentheses after function name, it will make it to execute.
您將使用此主函數來執行傳遞的函數定義,如下所示:
masterFunc(foo,{a:1}) #Sample execution
在Python中,函數是對象,就像其他所有對象一樣。 您可以將函數作為參數傳遞並非常簡單地執行它們。
在你的情況下,
def say_hello(name):
print "hi ", name
def say_bye(name, time):
print name, ", have a good ", time
say_bye("john", "night")
john , have a good night
def master(fun, **kwargs):
fun(**kwargs)
master(say_bye, name='john', time='night')
john , have a good night
params1 = {'name': 'jay', 'time': 'morning'}
params2 = {'name': 'cole'}
master(say_hello, **params2)
hi cole
master(say_bye, **params1)
jay , have a good morning
這應該工作。
您可以嘗試以下方法。
class A:
def a(self, *args, **kwargs):
print('A')
def b(self, *args, **kwargs):
print('B', args, kwargs)
def main(func, *args, **kwargs):
x = A()
if hasattr(x, func):
func = getattr(x, func)
func(*args, **kwargs)
else:
print('No function name {} defined under class'.format(func))
if __name__ == '__main__':
func = raw_input('Func_name: a/b')
main(func, (1), {1:1})
~/del$ python test.py
Func_name: a/ba
True
A
~/del$ python test.py
Func_name: a/bb
True
('B', (1, {1: 1}), {})
~/del$
在這里,我們在__builtin__
使用getattr
函數。
*首先,它檢查class A
的實例下是否有一個名為a
或b
的函數/方法。 *如果是的話,那么只有將getattr
距離,並執行傳遞指定參數和kwargs。 *如果有人通過了未定義的函數名,它將不會崩潰並返回在那兒說需要的語句。
希望這可以幫助 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.