1. 程式人生 > >python學習筆記(4) 裝飾器

python學習筆記(4) 裝飾器

進制 time time() gin 版本 enc use 刪除 odin

import time

def timer(f):

  def inner():

    start = time.time()

    ret = f()

    end = time.time()

    print(end-start)

    return ret

  return inner #返回函數地址,沒有括號

@timer

def func():

  time.sleep(1)

  print‘大家好我是渣渣輝‘

  return ‘是兄弟就來砍我‘

ret = func() #此處實際上執行的是inner

print(ret)

#在不修改原函數的情況下添加功能,timer就是一個裝飾器函數

#################################################

裝飾器標準格式

def wrapper(f):

  def inner(*args,**kwargs):

    ret = f(*args,**kwargs)

    return ret

  return inner

裝飾器的本質:閉包函數

#################################################

from functools import wraps

def wrapper(func):

  @wraps(func)

  def inner(*args,**kwargs):

    print(‘大家好‘)

    ret = func(*args,**kwargs)

    print(‘這是你沒玩過的全新版本‘)

    return ret

  return inner

@wrapper #legend = wrapper(legend)

def legend(a):

  print(‘我是%s‘%(a))

  return ‘是兄弟就來砍我‘

print(legend.__name__)

print(legend.__doc__)

ret = legend(‘渣渣輝‘)

print(ret)

#演示裝飾器和函數的執行順序

######################################################

為多個函數增加記錄調用功能,先將被調用的函數名稱寫入文件

def log(func):

  def inner(*args,**kwargs):

    with open(‘log‘,‘a‘,encoding= utf8) as f:

      f.write(func.__name__+‘\n‘)

    ret = func(*args,**kwargs)

    return ret

  return inner

@log

def shoplist_add():

  print(‘購物車增加一件商品‘)

@log

def shoplist_del():

  print(‘購物車刪除一件商品‘)

###################################################

為多個函數增加單次登陸驗證

FLAG = 0

def login(func):

  def inner(*args,**kwargs):

  global FLAG

  if FLAG:

    ret = func(*args,**kwargs)

    return ret

  else:

    uername = input(‘請輸入用戶名:‘)

    userpwd = input(‘請輸入密碼:‘)

    if username == ‘天使萌‘ and userpwd ==‘123‘:

      FLAG = 1

      ret = func(*args,**kwargs)

      return ret

    else:

      print(‘登陸失敗‘)

  return inner

@login

def shoplist_add():

  print(‘購物車增加一件商品‘)

@login

def shoplist_del():

  print(‘購物車刪除一件商品‘)

shoplist_add()

shoplist_add()

shoplist_del()

shoplist_del()

###############################################

讀取網頁內容並儲存到文件,如果文件有內容則直接從文件讀取

import os

from urllib.request import urlopen

def cache(func):

  def inner(*args,**kwargs):

    if os.path.filesize(‘web_cache‘):

      with open(‘web_cache‘,‘wb‘) as f:

        return f.read()

    ret = func(*args,**kwargs)

    with open(‘web_cache‘,‘wb‘) as f:

      f.write(b‘*****‘+ret) #以十六進制寫入

    return ret

  return inner

@cache

def get(url):

  code = urlopen(url).read()

  return code

ret = get(‘baidu.com‘)

print(‘ret‘)

python學習筆記(4) 裝飾器