python中裝飾器的使用

2021-08-21 11:00:28 字數 1552 閱讀 7930

使用閉做包裝飾器

def filter(func):

def test(username,password):

if username == 'admin' and password == '123456':

func(username,password)

else:

print('登入失敗')

return test

@filter

def login(username,password):

print('登入成功')

username = input('請輸入使用者名稱:')

password = input('請輸入密碼:')

login(username,password)

使用類做裝飾器

class filter(object):

def __init__(self,func):

self.func = func

def __call__(self,username,password):

if username == 'admin' and password == '123456':

self.func(username,password)

else:

print('登入失敗')

@filter

def login(username,password):

print('登入成功')

username = input('請輸入使用者名稱:')

password = input('請輸入密碼:')

login(username,password)

使用多層裝飾器

def filter_username(func):

print('username')

def test(username,password):

if username == 'admin':

func(username,password)

else:

print('使用者名稱錯誤')

return test

def filter_password(func):

print('password')

def test(username,password):

if password == '123456':

func(username,password)

else:

print('密碼錯誤')

return test

@filter_username

@filter_password

def login(username,password):

print('登入成功')

username = input('請輸入使用者名稱:')

password = input('請輸入密碼:')

login(username,password)

*裝飾器先從最外層開始裝飾

Python中裝飾器的使用

在學習cs20si中遇到了裝飾器,所以這裡介紹下裝飾器decorator的使用。主要內容依據 python中,所有的東西都是物件,乙個函式可以被賦到變數中,傳遞給另乙個函式,或者被其他函式作為返回值。python的裝飾器就是乙個函式,接受函式作為引數,並且用另乙個函式作返回值。import time...

Python中裝飾器的使用

說明 掌握python中裝飾器的使用 1.裝飾器解決什麼問題?不改變函式的結構,為函式新增功能就是我們的裝飾器 在需要新增功能的函式上面加上乙個 裝飾器即可完成對函式的功能新增。如 decorator deftest pass2.裝飾器的定義與裝飾器的本質?2.1 裝飾器的定義 deflog f d...

python中裝飾器

對修改是封閉的,對擴充套件是開放的 import time def f1 print time.time print this is a function.def f2 print this is a function.print time.time f1 def print current tim...