Python基礎知識之裝飾器decorator

2021-08-13 05:14:44 字數 1688 閱讀 5001

本質是函式,(裝飾其他函式)為其他函式新增附加功能。

不能修改被裝飾的函式的源**

不能修改被裝飾的函式的呼叫方式

高階函式+巢狀函式=》裝飾器

1. 函式即「變數」:

定義乙個函式就相當於定義乙個變數,即將函式體賦值給乙個變數名。python的記憶體**機制規定:當儲存在記憶體中的內容沒有對應的變數名指定時,則當記憶體**機制定期清理記憶體的時候則**記憶體。

2. 高階函式:

def bar():

print("in the bar")

# test1就是乙個高階函式

def test1(func):

print(func)

func()

test1(bar)

3. 巢狀函式:
在乙個函式的函式體內用def宣告乙個新的函式。

def func1():

def func2():

pass

import time

# 這裡的timer就是乙個裝飾器

def timer(func):

def deco(*args, **kwargs):

start_time = time.time()

func(*args, **kwargs)

end_time = time.time()

print("the func run time is %s" %(end_time-start_time))

return deco

# 裝飾器的呼叫

@timer # test1 = timer(test1)

def test1():

time.sleep(3)

print("in the test1")

test1()

user, passwd = 'bear', 'abc123'

def auth(auth_type):

print("auth func:",auth_type)

if auth_type == "local":

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

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

if user == username and passwd == password:

print("user has passed authtication")

res = func(*args, **kwargs)

return res

else:

exit("invalid username or password")

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")

def bbs():

print("welcome to bbs page")

python基礎知識整理 裝飾器

最簡裝飾器 def deco func def wrap args,kwargs return func args,kwargs return wrap deco def foo a,b return a b原理 對比被裝飾前後的foo.name 和foo.doc from functools im...

Python基礎知識之迭代器

我們已經知道,可以直接作用於 for 迴圈的資料型別有以下幾種 from collections import iterable isinstance iterable true isinstance iterable true isinstance abc iterable true isinst...

Python基礎知識之迭代器

我們已經知道,可以直接作用於 for 迴圈的資料型別有以下幾種 from collections import iterable isinstance iterable true isinstance iterable true isinstance abc iterable true isinst...