编程语言
首页 > 编程语言> > Python 装饰器学习记录

Python 装饰器学习记录

作者:互联网

基础教程:
https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。
装饰器让你在一个函数的前后去执行代码

装饰器模型

def a_new_decorator(a_func):	# 装饰器
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
 
def a_function_requiring_decoration():	
    print("I am the function which needs some decoration to remove my foul smell")
 
a_function_requiring_decoration()	# 不带装饰器的函数
#outputs: "I am the function which needs some decoration to remove my foul smell"
 
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# 带装饰器的函数,把原函数作为参数,经过装饰器返回函数,并赋值到原函数
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
 
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()


向decorator传入参数
decorator必须仅接受一个被修饰的函数为参数,这也是为什么我们必须再外包裹一层从而接受那些额外的参数并且产生我们的decorator的原因。这个例子中tags函数是我们的decorator generator

def tags(tag_name):
    def tags_decorator(func):
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    return "Hello "+name

print get_text("John")

# Outputs <p>Hello John</p>


目标:用装饰器写多次尝试连接

标签:function,记录,Python,some,decoration,def,func,装饰,decorator
来源: https://blog.csdn.net/chenbaixing/article/details/118941199