# 1 装饰器

## 1.1 用装饰器给函数添加一个包装

```def CutDown(n):
import time
start = time.time()

while n > 0:
n -= 1

end = time.time()

print(end-start)

CutDown(10000000)

```def GetRunTime(func):
import time
from functools import wraps

@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result

return wrapper

@GetRunTime
def cutdown(n):
while n > 0:
n -= 1

cutdown(10000000)

## 1.2 运用装饰器时保存函数的元数据

```def GetRunTime(func):
import time
#from functools import wraps

# @wraps(func)
def wrapper(*args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end - start)
return result

return wrapper

@GetRunTime
def cutdown(n):
"""
:param n:
:return:
"""
while n > 0:
n -= 1

cutdown(10000000)
print(cutdown.__name__)
print(cutdown.__doc__)```

```cutdown 1.4844520092010498
wrapper

:param args:
:param kwargs:
:return:```

```cutdown 1.193265676498413
cutdown

:param n:
:return:```

## 1.3 对装饰器进行解包

```@GetRunTime
def cutdown(n):
"""
:param n:
:return:
"""
print('cundown is running')
while n > 0:
n -= 1

cutdown.__wrapped__(10000000)

cundown is running```

115 篇文章45 人订阅

0 条评论

## 相关文章

4.5K40

5K20

4K30

6.7K20

### 腾讯云主机Python3环境安装Scrapy爬虫框架过程及常见错误

Scrapy安装介绍Scrapy的安装有多种方式，它支持Python2.7版本及以上或Python3.3版本及以上。下面说明Python3环境下的安装过程。Sc...

2.6K10

6.4K10

38210

2K10

10.4K30

7.1K60