溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python裝飾器用法與知識(shí)點(diǎn)小結(jié)

發(fā)布時(shí)間:2020-10-21 10:10:47 來源:腳本之家 閱讀:121 作者:WFaceBoss 欄目:開發(fā)技術(shù)

本文實(shí)例講述了Python裝飾器用法與知識(shí)點(diǎn)。分享給大家供大家參考,具體如下:

(1)裝飾器含參數(shù),被裝飾函數(shù)不含(含)參數(shù)

實(shí)例代碼如下:

import time
# 裝飾器函數(shù)
def wrapper(func):
  def done(*args,**kwargs):
    start_time = time.time()
    func(*args,**kwargs)
    stop_time = time.time()
    print('the func run time is %s' % (stop_time - start_time))
  return done
# 被裝飾函數(shù)1
@wrapper
def test1():
  time.sleep(1)
  print("in the test1")
# 被裝飾函數(shù)2
@wrapper
def test2(name):  #1.test2===>wrapper(test2)  2.test2(name)==dome(name)
  time.sleep(2)
  print("in the test2,the arg is %s"%name)
# 調(diào)用
test1()
test2("Hello World")

(2)裝飾器含有參數(shù),被裝飾函數(shù)含(不含)參數(shù)

import time
user,passwd = 'admin','admin'
def auth(auth_type):
  print("auth func:",auth_type)
  def outer_wrapper(func):
    def wrapper(*args, **kwargs):
      print("wrapper func args:", *args, **kwargs)
      if auth_type == "local":
        username = input("Username:").strip()
        password = input("Password:").strip()
        if user == username and passwd == password:
          print("\033[32;1mUser has passed authentication\033[0m")
          res = func(*args, **kwargs) # from home
          print("---after authenticaion ")
          return res
        else:
          exit("\033[31;1mInvalid username or password\033[0m")
      elif auth_type == "ldap":
        print("ldap鏈接")
    return wrapper
  return outer_wrapper
@auth(auth_type="local") # home = wrapper()
def home():
  print("welcome to home page")
  return "from home"
@auth(auth_type="ldap")
def bbs():
  print("welcome to bbs page"
print(home()) #wrapper()
bbs()

總結(jié):

(1)裝飾器實(shí)質(zhì)為函數(shù)內(nèi)嵌,返回函數(shù)地址。

(2)裝飾器帶參數(shù)與不帶參數(shù)相比裝飾器帶參數(shù)的多了一層函數(shù)定義用于接收裝飾器中傳遞的參數(shù),其余基本相同。

(3)先驗(yàn)證裝飾器中的參數(shù),在驗(yàn)證普通函數(shù)的參數(shù)

小知識(shí):

列表生產(chǎn)式:[i for i in range(5)]---->[0,1,2,3,4,5]

生成器與迭代器:

第一種方式通過括號(hào)的方式生成

生成器:()---(i for i in range(5))  ==>generator

這種一邊循環(huán)一邊計(jì)算的機(jī)制,稱為生成器:generator。

生成器只有在調(diào)用時(shí)才會(huì)生成相應(yīng)的數(shù)據(jù),只記錄當(dāng)前位置。

只有一個(gè)__next__()方法

第二種方式通過yield生成

在函數(shù)中使用yield即可將一個(gè)函數(shù)變?yōu)橐粋€(gè)生成器

迭代器:

直接作用于for循環(huán)的數(shù)據(jù)類型:

一類是集合數(shù)據(jù)類型,如list、tuple、dict、set、str等;

一類是generator,包括生成器和帶yield的generator function。

直接作用于for循環(huán)的對(duì)象統(tǒng)稱為可迭代對(duì)象:Iterable。

可以使用isinstance()判斷一個(gè)對(duì)象是否是Iterable對(duì)象

from collections import Iterable
 isinstance([], Iterable)=========true

*可以被next()函數(shù)調(diào)用并不斷返回下一個(gè)值的對(duì)象稱為迭代器:Iterator。

可以使用isinstance()判斷一個(gè)對(duì)象是否是Iterator對(duì)象:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
======>True

生成器都是Iterator對(duì)象,但list、dict、str雖然是Iterable,卻不是Iterator。

把list、dict、str等Iterable變成Iterator可以使用iter()函數(shù):

例如:iter([])<====迭代器

Python的Iterator對(duì)象表示的是一個(gè)數(shù)據(jù)流,Iterator對(duì)象可以被next()函數(shù)調(diào)用并不斷返回下一個(gè)數(shù)據(jù),直到?jīng)]有數(shù)據(jù)時(shí)拋出StopIteration錯(cuò)誤??梢园堰@個(gè)數(shù)據(jù)流看做是一個(gè)有序序列,但我們卻不能提前知道序列的長度,只能不斷通過next()函數(shù)實(shí)現(xiàn)按需計(jì)算下一個(gè)數(shù)據(jù),所以Iterator的計(jì)算是惰性的,只有在需要返回下一個(gè)數(shù)據(jù)時(shí)它才會(huì)計(jì)算。

Iterator甚至可以表示一個(gè)無限大的數(shù)據(jù)流,例如全體自然數(shù)。而使用list是永遠(yuǎn)不可能存儲(chǔ)全體自然數(shù)的。

小結(jié):

凡是可作用于for循環(huán)的對(duì)象都是Iterable類型;

凡是可作用于next()函數(shù)的對(duì)象都是Iterator類型,它們表示一個(gè)惰性計(jì)算的序列;

集合數(shù)據(jù)類型如list、dict、str等是Iterable但不是Iterator,不過可以通過iter()函數(shù)獲得一個(gè)Iterator對(duì)象。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI