python之閉包函數 裝飾器 作業

來源:互聯網
上載者:User

標籤:檔案中   閉包函數   內容   dom   帳號   bsp   end   rgs   頁面   

一:編寫函數,(函數執行的時間是隨機的)

import random
def t():
time.sleep(random.randrange(1,3))
print(‘hello‘)
二:編寫裝飾器,為函數加上統計時間的功能

import time
import random
def timebe(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res = func(*args, **kwargs)
end_time=time.time()
print(‘已耗用時間是:%s‘ % (end_time - start_time))

return res
return wrapper

@timebe
def t():
time.sleep(random.randrange(2,3))
print(‘hello‘)


三:編寫裝飾器,為函數加上認證的功能

def ident(func):
def wrapper(*args,**kwargs):
name=input(‘name:‘)
pwd=input(‘pwd: ‘)
if name==‘zuo‘ and pwd==‘123‘:
print(‘correct‘)
return func(*args, **kwargs)
else:
print(‘wrong‘)
return wrapper


@ident
def t():
print(‘hello‘)



四:編寫裝飾器,為多個函數加上認證的功能(使用者的帳號密碼來源於檔案),要求登入成功一次,後續的函數都無需再輸入使用者名稱和密碼
    注意:從檔案中讀出字串形式的字典,可以用eval(‘{"name":"egon","password":"123"}‘)轉成字典格式



五:編寫下載網頁內容的函數,要求功能是:使用者傳入一個url,函數返回下載頁面的結果

六:為題目五編寫裝飾器,實現緩衝網頁內容的功能:
    具體:實現下載的頁面存放於檔案中,如果檔案內有值(檔案大小不為0),就優先從檔案中讀取網頁內容,否則,就去下載,然後存到檔案中

七:還記得我們用函數對象的概念,製作一個函數字典的操作嗎,來來來,我們有更高大上的做法,在檔案開頭聲明一個空字典,然後在每個函數前加上裝飾器,
完成自動添加到字典的操作

python之閉包函數 裝飾器 作業

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.