[英]How to Implement decorator which returns function signature and it's return value?
如何实现返回 function 签名及其返回值的装饰器?
def some(func): """:param func: function """ # 这里是你的代码
@some def add(a, b): 返回 a + b
添加(4, 5)
它应该返回:# add(4, 5) 被调用并返回 9'。 不知道如何意识到这一点。 有人可以帮忙吗?
创建装饰器对于编程新手或 python 来说可能很棘手。装饰器的一般模式是:
def decorator(func):
def wrapper(*args, **kwargs):
# Do stuff
return func(*args, **kwargs)
return wrapper
虽然起初看起来很复杂,但装饰器基本上将您创建的 function 作为输入(在本例中为add
)。 然后它用wrapper
function 包装您的add
function。这允许您在调用add
function 之前或之后注入您喜欢的任何逻辑。
我在下面包含了一些代码来解决您的特定问题。
def print_each_call(func):
def wrapper(*args, **kwargs):
output = func(*args, **kwargs)
print(f'function {func.__name__}{args} was called and output {output}')
return output
return wrapper
@print_each_call
def add(a, b):
return a + b
print(add(1, 2))
# output (first line is from the decorator. Second line is from print()):
# function add(1, 2) was called and output 3
# 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.