Python3 5 裝飾器及應用詳解(下)

2021-08-07 21:17:49 字數 2464 閱讀 9227

1、裝飾器應用——模擬**登入頁面,訪問需要認證登入頁面

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# author:zhengzhengliu

#模擬**,訪問頁面和部分需要登入的頁面

import timer

user,passwd = "liu","liu123"

def auth(func):

username = input("username:").strip()

password = input("password:").strip()

if username == user and password == passwd:

print("\033[32;1muser has passed authentication!\033[0m")

res = func(*args,**kwargs)

print("-----after authentication---")

return res

else:

exit("\033[31;1minvalid username or password!\033[0m")

def index():

print("welcome to index page!")

@auth

def home():

print("welcome to index home!")

return "from home"

@auth

def bbs():

print("welcome to index bbs!")

#函式呼叫

index()

print(home())

bbs()

#執行結果:

#welcome to index page!

#username:liu

#password:liu123

#user has passed authentication!

#welcome to home page!

#-----after authentication---

#from home

#username:liu

#password:liu123

#user has passed authentication!

#welcome to bbs page!

#-----after authentication---

2、裝飾器帶引數

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# author:zhengzhengliu

#模擬**,訪問頁面和部分需要登入的頁面,多種認證方式

import timer

user,passwd = "liu","liu123"

def auth(auth_type):

print("auth func:",auth_type)

if auth_type == "local":

username = input("username:").strip()

password = input("password:").strip()

if username == user and password == passwd:

print("\033[32;1muser has passed authentication!\033[0m")

#被裝飾的函式中有返回值,裝飾器中傳入的引數函式要有返回值

res = func(*args, **kwargs) #from home

print("-----after authentication---")

return res

else:

exit("\033[31;1minvalid username or password!\033[0m")

elif auth_type == "ldap":

print("ldap....")

def index():

print("welcome to index page!")

def home():

print("welcome to home page!")

return "from home"

@auth(auth_type="ldap") #利用遠端的ldap登入

def bbs():

print("welcome to bbs page!")

#函式呼叫

index()

bbs()

執行結果:

Python3 5 裝飾器之案例剖析

usr bin env python coding utf 8 author zhengzhengliu 高階函式 巢狀函式 裝飾器 import time def timer func timer test1 func test1 def decor start time time.time fu...

python 裝飾器應用

裝飾器應用 裝飾器的主要作用是 列印日誌,檢測效能,資料庫事物,url路由 應用1,生成標籤 def bold fn def 閉包,這個函式的作用就是給原來的函式增加一些功能,return fn bold deftest return python in 2 test out 2 python 等價...

python中的 property裝飾器詳解

coding utf 8 property 負責裝飾乙個物件函式,讓其生成對應的 setter 和getter 函式,呼叫的時候可以直接使用物件名 函式名 函式名不加括的形式,這種類似屬性的呼叫方式來執行函式 class man object property 裝飾的物件函式就是乙個 getter ...