標籤:講解 test 函數名 定義 rgs art port 原則 top
[TOC]
#48.第四周-第01章節-Python3.5-上節內容回顧
#50.第四周-第03章節-Python3.5-裝飾器詳解
1.裝修器定義:裝飾器本質是函數,(裝飾其它函數)就是為其它函數添加附件功能
2.原則:a)不能修改被裝飾函數的原始碼
b)不能修改被裝飾函數的調用方式
#51.第四周-第04章節-Python3.5-裝飾器應用詳解
#52.第四周-第05章節-Python3.5-裝飾器之函數即變數
#53.第四周-第06章節-Python3.5-裝飾器之高階函數
高階函數:
a)把一個函數名當作實參傳給另一個函數(可以實現裝修器中的:不能修改被裝飾函數的原始碼的情況下為函數增加功能)
```
def bar():
print("in the bar")
def test(func):
print(func)
func()
test(bar)
```
b)傳回值中包含函數名(可以實現裝修器中的:不修改函數的調用方式)
```
import time
def bar():
time.sleep(3)
print("in the bar")
def test(func):
print(func)
return func
# print(test(bar))
bar = test(bar)
bar() #run bar
```
#54.第四周-第07章節-Python3.5-裝飾器之嵌套函數
高階函數 + 嵌套函數 => 裝修器
```
x = 0
def gradpa():
x = 1
def dad():
x = 2
def son():
x = 3
print(x)
son()
dad()
gradpa()
```
#55.第四周-第08章節-Python3.5-裝飾器之案例剖析1
裝飾器一:
```
import time
def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco
@timer
def test1():
time.sleep(2)
print("in the test1")
test1()
```
#56.第四周-第09章節-Python3.5-裝飾器之案例剖析2
裝飾器二:解決參數傳遞問題
```
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco
@timer
def test1():
time.sleep(2)
print("in the test1")
@timer
def test2(name,age):
time.sleep(2)
print("in the test2:",name,age)
test1()
test2("alex",age = 32)
```
#57.第四周-第10章節-Python3.5-裝飾器之高潮講解
week4_自學python_decorator