美文网首页
Python装饰器10-参数传递

Python装饰器10-参数传递

作者: dnsir | 来源:发表于2019-06-15 11:55 被阅读0次

1 被装饰的函数有参数怎么办?

from functools import wraps
"""
参数传递方式
"""
def logit(func):
    @wraps(func)
    # 参数传递,影响这儿
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

"""
参数传递
"""
@logit
def addition_func(x):
    return x + x

result= addition_func(4)
print(result)

小结

新函数with_logging参数定义为*args, **kwargs,因为新函数with_logging的地址空间就是待装饰的函数名addition_func的新地址。

相关文章

网友评论

      本文标题:Python装饰器10-参数传递

      本文链接:https://www.haomeiwen.com/subject/nhfbfctx.html