裝飾器2

来源:https://www.cnblogs.com/zhangfanshixiaobai/archive/2023/09/11/17694426.html
-Advertisement-
Play Games

裝飾器 裝飾器的簡易版本 import time def index(): time.sleep(3) print('from index') def home(): print('from home') def func(): print('from func') def outer(func_n ...


裝飾器

裝飾器的簡易版本

import time
def index():
    time.sleep(3)
    print('from index')
    
    
def home():
    print('from home')
    
def func():
    print('from func')
    
    
def outer(func_name): 
    # func_name = index 
    def get_time():
        # 1. 函數執行之前打一個時間點
        start_time = time.time()
        func_name() # index() home()


        # 2. 在函數執行之後,在打一個時間點
        end_time = time.time()

        print('總共執行了:%s' % (end_time - start_time))
	return get_time

# get_time(index)
# get_time(home)

index=outer(index)  # res=get_time
index() # get_time()

裝飾器解決參數問題

import time
def index():
    time.sleep(3)
    print('from index')
    
    
def home(name, u, a):
    print('from home')
    return 'from home'
def func():
    print('from func')
    
    
def outer(func_name): 
    # func_name = index 
    def get_time(*args, **kwargs): args=() kwargs={'username':jerry, 'age':18}
        # 1. 函數執行之前打一個時間點
        
        start_time = time.time()
        func_name(*args, **kwargs) # index() home()
        res=func_name(name, username='jerry', age=18) # index() home()


        # 2. 在函數執行之後,在打一個時間點
        end_time = time.time()

        print('總共執行了:%s' % (end_time - start_time))
        return res
	return get_time

# get_time(index)
# get_time(home)

index=outer(index)  # res=get_time
index() # get_time()


home=outer(home)  # res=get_time
res=home('kevin', username='jerry', age=18) # get_time()
print(res) #  None


"""認證登錄的裝飾器,當你訪問函數的時候,必須登錄之後才能夠訪問!"""

裝飾器的固定模板

def index():
    pass


def outer(func_name):
    def inner(*args, **kwargs):
        '''添加一些函數執行之前的功能'''
        res=func_name(*args, **kwargs) # 這個就是執行的真正的函數
        '''添加一些函數執行之後的功能'''
        return res
    
    return inner

'''裝飾器本質上還是函數!'''

@outer
@outer # index=outer(index)
def index():
    pass

# index=outer(index)
index()

"""
1. 語法糖的書寫規範
	@裝飾器名字
	把語法糖緊貼著寫在函數的頭部
2. 裝飾器原理:
	把被裝飾對象當成函數的參數傳遞給裝飾器的形參
"""

雙層語法糖

import time


def outer(func):
    def get_time(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)  # 只能夠統計index函數的時間
        end_time = time.time()
        print('執行時間:%s' % (end_time - start_time))
        return res

    return get_time

def login_auth(func):
    # func = index
    def auth():
        username = input('username:>>>').strip()
        password = input('password:>>>').strip()
        # 2. 比較用戶名和密碼
        if username == 'jerry' and password == '123':
            # 執行函數
            print('登錄成功')
            func()
        else:
            print('用戶名或者密碼錯誤')
    return auth

@login_auth # index=login_auth(get_time) # index=auth
@outer      # get_time=outer(index)
def index():
    time.sleep(3)
    print('from index')

index() # auth()

三層語法糖(多層)

# 判斷七句print執行順序
def outter1(func1):
    print('載入了outter1')
    def wrapper1(*args, **kwargs):
        print('執行了wrapper1')
        res1 = func1(*args, **kwargs)
        return res1
    return wrapper1

def outter2(func2):
    print('載入了outter2')
    def wrapper2(*args, **kwargs):
        print('執行了wrapper2')
        res2 = func2(*args, **kwargs)
        return res2
    return wrapper2

def outter3(func3):
    print('載入了outter3')
    def wrapper3(*args, **kwargs):
        print('執行了wrapper3')
        res3 = func3(*args, **kwargs)
        return res3
    return wrapper3


@outter1
@outter2
@outter3
def index():
    print('from index')
index()

裝飾器的修複技術(瞭解)

import time

from functools import wraps
def outer(func):
    @wraps(func) # 修複技術
    def get_time():
        start_time = time.time()
        func()  # 只能夠統計index函數的時間
        end_time = time.time()
        print('執行時間:%s' % (end_time - start_time))
    return get_time

# @outer  # index=outer(index)
def index():
    print('from index')

'''修複技術就是為了讓裝飾器偽裝的更像'''
# index()
# print(index) # <function index at 0x000002F69849A940>
# print(index) # <function index at 0x000002F69849A940>
# help(index)


@outer
def home():
    '''這是home函數'''

help(home)

有參裝飾器(重要)



def outter(source_type, *args1, **kwargs1):
    # 'file', 1, 2, 3, 4, 5, 6,
    # source_type = 'file'
    def login_auth(func):  # 參數個數只能有一個
        def auth(*args, **kwargs): #
            username = input('username:>>>').strip()
            password = input('password:>>>').strip()
            # 2. 比較用戶名和密碼
            """
                1. 文件中獲取用戶名和密碼
                2. 從MySQL中獲取用戶名和密碼
                3. 從oracle中獲取用戶名和密碼
                4. 從postgresql中獲取用戶名和密碼
            """
            # print(a, b, c, d, e, f)
            if source_type == 'file':
                print('文件中獲取用戶名和密碼')
            elif source_type == 'mysql':
                print('從MySQL中獲取用戶名和密碼')
            elif source_type == 'oracle':
                print('從oracle中獲取用戶名和密碼')
            elif source_type == 'postgresql':
                print('從postgresql中獲取用戶名和密碼')

            if username == 'jerry' and password == '123':
                # 執行函數
                print('登錄成功')
                func(source_type, *args, **kwargs)
            else:
                print('用戶名或者密碼錯誤')
        return auth
    return login_auth

@outter('file', 1, 2, 3, 4, 5, 6,) # login_auth(home, file)
# @login_auth # login_auth(home, file)
def home():
    pass

home('mysql')

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 介紹 ESLint 是一個根據方案識別並報告 ECMAScript/JavaScript 代碼問題的工具,其目的是使代碼風格更加一致並避免錯誤。在很多地方它都與 JSLint 和 JSHint 類似,除了: ESLint 使用 Espree 對 JavaScript 進行解析。 ESLint 在代碼 ...
  • 1. 安裝 vue-i18n npm i vue-i18n -S 2. 創建一個i8n的配置文件 如:i18nConfig.js // 配置 vue-i18n 實現國際化語言設置 import { createI19n } from 'vue-i18n' import zh_cn from '../ ...
  • 最近系統學習了vue.js 的官方腳手架create-vue的源碼,深入分析了裡面的技術實現細節,本文是我整理的源碼學習文章。 ...
  • 很早之前,就寫過一篇與原生嵌套相關的文章 -- CSS 即將支持嵌套,SASS/LESS 等預處理器已無用武之地?,彼時 CSS 原生嵌套還處於工作草案 Working Draft (WD) 階段,而今天(2023-09-02),CSS 原生嵌套 Nesting 終於成為了既定的規範! CSS 原生 ...
  • 淺拷貝 當我們想要複製一段數據的時候嗎,我們就會用到拷貝;拷貝數據又分為了淺拷貝和深拷貝,淺拷貝指複製對象或數組的頂層結構,如果對象或數組中有引用類型的屬性值,複製的是引用(地址)而非值;而深拷貝則是遞歸複製完整的對象或數組,包括嵌套的子對象或子數組,生成一個全新的對象,新對象和原對象的引用地址不同 ...
  • 前言 大家好,我是 god23bin,今天我們來聊一聊 Spring 框架中的 Bean 作用域(Scope)。 什麼是 Bean 的作用域? 我們在以 XML 作為配置元數據的情況下,進行 Bean 的定義,是這樣的: <bean id="vehicle" class="cn.god23bin.d ...
  • 1 ★★★ 例1 : 判斷集合是否為空: 2 CollectionUtils.isEmpty(null); //控制台列印:true 3 CollectionUtils.isEmpty(new ArrayList());//控制台列印:true 4 CollectionUtils.isEmpty({ ...
  • 使用<property>標簽的value屬性配置原始數據類型和ref屬性配置對象引用的方式來定義Bean配置文件。這兩種情況都涉及將單一值傳遞給Bean。那麼如果您想傳遞多個值,例如Java集合類型,如List、Set、Map和Properties怎麼辦?為了處理這種情況,Spring提供了四種類型 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...