- 函数装饰器定义
python装饰器本质上就是一个函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外的功能;
装饰器的返回值也是一个函数对象(函数的指针)
- 例子:
def startEnd(fun): #函数命名的规则,驼峰
def wraper():
print("!!!!!!!start!!!!!!!!!")
fun()
print("!!!!!!!end!!!!!!!!!")
return wraper
@startEnd
def hello():
print("hello world")
hello()
脚步输出:
- 装饰器的作用
2. 装饰器通过@(符号)进行使用 ,相当于把hello() 函数作为参数,传给startEnd()
3. @startEnd 相当于 hello = startEnd(hello)
4. 当你调用hello()的时候,是不是就相当于调用了startEnd(hello())()
- 装饰器的属性特点
实质: 是一个函数
参数:是你要装饰的函数名(并非函数调用)
返回:是装饰完的函数名(也非函数调用)
作用:为已经存在的对象添加额外的功能
特点:不需要对对象做任何的代码上的变动
- 装饰器的写法
例子1:
def hello(): print("!!!!!!!!!start!!!!!!!!") print("hello world") print("!!!!!!!!end!!!!!!!!!") a = hello() #hello函数把返回值 赋予 a print("#####################") b = hello #b是一个函数, b()相当于hello() print("@@@@@@@@@@") b()
输出结果:
例2:
def startEnd(fun):
def aa(name):
print("*********start*******")
fun(name)
print("*********end*******")
return aa
# 返回值 aa函数
# hello() 相当于执行 hello()
@startEnd
#装饰器
def hello(name):
print("hello {0}".format(name))
hello("hewj")
结果输出:
理解思路
1. aa = startEnd(hello)
2. hello = aa
3. 调用hello()
例3:带参数的装饰器函数
def startEnd(author):
def a(fun):
def b(name):
print("This author is {0}".format(author))
print("*************start**********")
fun(name)
print("**************end***********")
return b
return a
@startEnd("hewj")
def hello(name):
print("hello {0}".format(name))
输出:
