装饰器

2019-05-12 09:49:24阅读 18评论 0

应用场景

定义了一些方法,在项目中大量使用。现在由于需求发生变化,需要在之前的方法上新增一些功能,但不能对之前方法进行修改。

举例

之前定义了一个方法do,现在要对其新增一个功能,即执行时计算出执行时间。

实现

```python

import time  

#定义装饰器函数  
def wrap(f):  
    def inner():  
        t1 = time.time()  
        f()  
        t2 = time.time()  
        print("函数执行时间为:%d秒"%(t2-t1))  
    return inner  

@wrap#将装饰器函数放在do函数上  
def do():  
    time.sleep(3)  
    print('hello')  

do()#执行,查看结果
执行结果
hello  
函数执行时间为:3秒  

Process finished with exit code 0
## 装饰器附加知识

装饰器会改变函数的__name__属性,如下:

1.未加装饰器时

python

def hi():  
    print('hello')  

print(hi.__name__)
结果
hi  

Process finished with exit code 0
2.加装饰器后

python

def wapper(func):  
    def inner(*args,**kwargs):  
        return func(*args,**kwargs)  
    return inner  

@wapper  
def hi():  
    print('hello')  

print(hi.__name__)
结果


inner

Process finished with exit code 0
3.改进方案

python

import functools  

def wapper(func):  
    @functools.wraps(func)#修饰inner  
    def inner(*args,**kwargs):  
        return func(*args,**kwargs)  
    return inner  

@wapper  
def hi():  
    print('hello')  

print(hi.__name__)
结果
hi  

Process finished with exit code 0

```

还没有评论,来说两句吧