一个函数可以打印Python中具有不同参数集的多个函数的返回值
我有许多函数一个函数可以打印Python中具有不同参数集的多个函数的返回值,python,function,parameter-passing,Python,Function,Parameter Passing,我有许多函数func_1,func_2func\n,每个参数都有自己的参数数量,但都返回数值或None 我想编写一个通用打印函数,该函数的第一个参数是func_1,func_2函数。如果返回值不是None,则应打印返回值 理想情况下,它应该是这样的: def universal_print(func, maybe_something_else_I_don't_know): if func is not None: print(func())
func_1
,func_2
func\n
,每个参数都有自己的参数数量,但都返回数值或None
我想编写一个通用打印函数,该函数的第一个参数是func_1
,func_2
<代码>函数。如果返回值不是None
,则应打印返回值
理想情况下,它应该是这样的:
def universal_print(func, maybe_something_else_I_don't_know):
if func is not None:
print(func())
我不明白如何将要打印的函数的参数传递到universal\u print
,因为每个函数都有自己的参数数量和类型
我的问题总的来说可以解决吗?如果是,怎么做?似乎是装饰师的完美工作:
from typing import Callable, Union
def universal_print(function_to_decorate: Callable) -> Callable:
def wrapper(*args, **kw):
# Calling your function
output = function_to_decorate(*args, **kw)
# Below this line you can do post processing
if output is not None:
print(f"your output : {output}")
return output
return wrapper
@universal_print
def return_if_odd(n:int) -> Union[int, None]:
if n%2:
return n
return None
使用它:
>>> return_if_odd(1)
your output : 1
1
>>> return_if_odd(2)
2
您可能不希望每次调用函数时都会执行decorator行为。在这种情况下,跳过装饰,直接使用该功能:
def return_if_odd(n:int) -> Union[int, None]:
if n%2:
return n
return None
可以使用*a、**kw分别获取参数:
def universal_print(func=None, *a, **kw):
if func is not None:
rv = func(*a, **kw)
if rv is not None:
print(rv)
universal_print(func, func_arg1, func_arg2, func_kwarg1=1)
或者可以在lambda中传递函数:
def universal_print(func=None):
if func is not None:
rv = func()
if rv is not None:
print(rv)
universal_print(lambda: func(func_arg1, func_arg2, func_kwarg1=1))
使用decorator的答案很好,但值得注意的是,decorator将用装饰过的函数替换您原来的函数。如果要保持原始函数的完整性,可以执行以下操作:
def universal_print(func: callable, /, *args, **kwargs):
result = func(*args, **kwargs)
if result is not None:
print(result)
return result
注:
- 我使用
和*args
传递任意位置和关键字参数**kwars
- 我使用的是Python 3.8中引入的“仅位置参数”语法(请参见参数列表中的斜杠)。如果传递给
的函数需要名为universal\u print
的参数,则可以防止冲突func
def universal_print(func: callable, /, *args, **kwargs):
result = func(*args, **kwargs)
if result is not None:
print(result)
return result