Python 裝飾器(裝飾器的簡單使用)


簡單介紹了裝飾器的一些基本內容,包含定義、本質、原則、如何實現。

1、裝飾器的定義

定義:一種增加函數功能的簡單方法,可以快速地給不同的函數或類插入相同的功能。

簡單點就是:高階函數+嵌套函數 -》裝飾器 

2、裝飾器本質

本質:函數 ,為其他函數進行裝飾。

舉個例子,現在有小狗100只,都有吃喝拉撒的功能,此時我想給其中50只小狗戴上裝飾帽的功能,這個裝飾帽就是裝飾器的功能。但是它並不會改變小狗本身原有的功能。

3、裝飾器的原則

原則1:不能修改被裝飾的函數的源代碼

原則2: 不能修改被裝飾的函數的調用方式

4、裝飾器的實現

大致了解需要有3個步驟:

4.1 函數即變量

4.2 高階函數

4.3 嵌套函數

舉個例子,裝飾器count_time()函數實現對one()函數添加統計函數運行時間的功能

import time
def count_time(func):
    def deco():
        start = time.time()
        func()
        end = time.time()
        print("the func run time  is %s" %(end-start))
    return deco
@count_time
//通過語法糖@count_time 直接對one()函數添加統計時間的功能
def one():
    time.sleep(0.5)
    print('in the one')

詳細步驟如下:

4.1函數即變量

舉個例子,比如把1賦值給x,內存會為x分配地址,且指向1 ;

此時x賦值給y,y同時也指向1;

 

同理,定義一個test()函數后,調用這個函數test(),內存會為這個函數分配一個地址,並指向函數體 

4.2 高階函數

高階函數一句話理解:函數中的變量包含函數。

A:把一個函數名當做實參傳給另外一個函數(在不修改被裝飾函數的源代碼情況下為其添加功能)

B:返回值中包含函數名(不修改函數的調用方式)

舉個例子,高階函數代碼如下:

import time
def count_time(func):
    def deco():
        start = time.time()
        func()
        end = time.time()
        print("the func run time  is %s" %(end-start))//程序運行時間:結束時間減去開始時間
   return deco

4.3 嵌套函數

很簡單的一句話:嵌套函數表示的是函數里面有函數。

舉個例子,one()函數中嵌套two()函數,嵌套函數代碼如下

def one():
     print('in the one')
     def two():
        print('in the two')
     two()
#調用函數
one()

5、裝飾器高級實現

裝飾器涉及到有參數的語法糖、無參數的語法糖,后續有時間可以再次進行詳細的了解~

user = 'xxx'
password = '123456'
def A(B):
    print("B:",B)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("wrapper func args:", *args, **kwargs)
            if B == "bb":
                user_name = input("Username:")
                pass_word = input("Password:")
                if user == user_name and password == pass_word:
                    print("User has passed authentication")
                    ret = func(*args, **kwargs) 
                    print("---after authenticaion ")
                    return ret
                else:
                    exit("Invalid username or password")
            elif B == "QWW":
                print("have question")
        return wrapper
    return outer_wrapper
def one():
    print("in the one")

@A(B="bb")
def two():
    print("in the two")
    return " I'm two"

@A(B="QWW")
def three():
    print("in the three")

one()
print(two())
three()

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM