python 装饰器

先对python里面的装饰做一个总结:

装饰器只是一种接受函数(就是那个你用“@”符号装饰的函数)的函数,并返回一个新的函数。

当你装饰一个函数,意味着你告诉Python调用的是那个由你的装饰器返回的新函数,而不仅仅是直接返回原函数体的执行结果。

# This is our decorator
def simple_decorator(f):
    # This is the new function we're going to return
    # This function will be used in place of our original definition
    def wrapper():
        print "Entering Function"
        f()
        print "Exited Function"

    return wrapper

@simple_decorator 
def hello():
    print "Hello World"

hello()

  运行上述代码会输出以下结果:

Entering Function
Hello World
Exited Function

 

1、首先,python里面的装饰器就是一个函数;

2、装饰器=高阶函数+嵌套函数;

def fuck(fn):
    print "fuck %s!" % fn.__name__[::-1].upper()
@fuck
def wfg():
    pass

此时,wfg=fuck(wfg),输出的结果是:fuck WFG

3、装饰器是为了让一个函数增加一个新的功能;

4、装饰器的执行顺序:有多个装饰器修饰的函数,优先执行距离最近的;

如下一段代码,先执行@get_time,再执行func(),最后执行@log

#@log
#@get_time
#def func():
# time.sleep(1)
# print("我正在执行。。。")
等价于:func=log(get_time(func))
注:装饰器类的引用需要加括号,函数的引用需要;

以下代码是个人的练习,仅供参观,不与评价,这是第一次写博客,也是第一次开始学习python,以后会每天都更一篇技术文档,不知道自己能坚持多久,现在刚刚入职公司做实习生一个月了,发现自己进步太慢,听人家说写技术文档可以给自己做一个巩固,再可以提升个人水平,写的有错的,不好的地方,欢迎大佬给予评价

#!/usr/bin/env python
#coding:utf-8
import time
#def circul():
# def inner():
# b=2
# print a
# print b
# return circul
#
#result=circul()
#print result


def log(func):
def wrapper(*args,**kwargs):
print("begin call %s"% func.__name__)
temp=func(*args,**kwargs)
print("after call%s"%func.__name__)
return temp
return wrapper

#@log
#def f():
# print("我正在执行。。。")
#f()

#def func():
# time.sleep(1)
# print("我正在执行。。。")
#
def get_time(foo):
def inner():
s_time=time.time()
foo()
e_time=time.time()
print("3我执行了%s秒"%(e_time-s_time))
return inner

def log(foo):
def inner():
print("2%s执行了"%foo.__name__)
foo()
return inner

#@log
#@get_time #->func=get_time(func)
#def func():
# time.sleep(1)
# print("我正在执行。。。")


##装饰器先执行离得近的装饰器 所以执行顺序为@get_time 函数f2 @log
@log
@get_time #->f2=get_time(f2)
def f2():
print("1我是f2" )

f2()

def logg(foo):
def inner(*args,**kwargs):
print("带参数:"%foo.__name__)
foo(*args,**kwargs)
return inner

@logg
def f3(x,y):
print (x,y)

f3(1,2)

##完整的装饰器
##高阶装饰器
def out_log(text):
def log(foo):
def inner(*args,**kwargs):
print(text)
res=foo(*args,**kwargs)
return res
return log

@out_log
def f4():
print("f4执行了")


#s_time=time.time()
#func()
#e_time=time.time()
#print("func执行了%s:"%(e_time-s_time))

#new_func=get_time(func)
#func=new_func
func()
#new_func()


 友情链接

     友情链接

原文地址:https://www.cnblogs.com/haoxinchen/p/8373078.html