week4_自學python_decorator

來源:互聯網
上載者:User

標籤:講解   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.