首页 > 编程语言 > 详细

python-函数装饰器

时间:2021-05-28 09:45:46      阅读:20      评论:0      收藏:0      [点我收藏+]

函数装饰器可以修改其他函数的功能,可以让代码更加简介

函数装饰器可以将函数作为参数传给另一个函数

先写个例子  

def hello():
    return  "hello"
def everyone(function):
    print("everyone")
    print(function())

#执行
everyone(hello)
#输出
everyone
hello

再上一个例子中,已经创建了一个装饰器,现在我们再来修改一下

def decorator_first(function):
    def Inside_function():
        print ("This is Inside_function_first")
        
        function()

        print("This is Inside_function_second")
       return Inside_function

def decorator_second():
    print ("This is Inside_function_third")

#执行
decorator_second=decorator_first(decorator_second)
decorator_second()
#输出
This is Inside_function_first
This is Inside_function_third
This is Inside_function_second

或许会疑惑,代码中并没有@符号,那下面用@符号重塑一下上面的例子

@decorator_first():
def decorator_second():
    print("This is Inside_function_third")
#执行
decorator_second()
#输出
This is Inside_function_first
This is Inside_function_third
This is Inside_function_second

 要是我们运行如下代码时,会有个问题

#执行
print(decorator_second.__name__)
#输出
Inside_function

这个输出应该为 decorator_second 这个函数被 Inside_function 替代了,我们可以用functools.wraps

from functools import wraps

def decorator_first(function):
    @wraps(function)
    def Inside_function_first():
    print ("This is Inside_function_first")
        
       function()

       print("This is Inside_function_second")
  return Inside_function
@
decorator_first
def decorator_second():
    print("This is Inside_function_third")

现在就可以了

 

python-函数装饰器

原文:https://www.cnblogs.com/wcacr/p/14819698.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!