python入門之裝飾器

2021-08-20 12:00:32 字數 2993 閱讀 5408

'''

#裝飾器(

#定義: 本質是函式,功能就是用來裝飾其它函式(就是為其他函式新增附加功能))

#原則:1.不能修改被裝飾的函式的源** 2.被修飾的函式的呼叫方式不能被修改

#實現裝飾器知識儲備:

#1.函式即「變數」 2.高階函式 3.巢狀函式 4.高階函式+巢狀函式=裝飾器

#----------函式即「變數」----------------------

#定義乙個函式就等於把函式體複製給了乙個變數

#-----------高階函式---------------------------

#滿足兩個條件之一:1.把乙個函式名當作實參傳給另外乙個函式(在不修改被裝飾函式源**的情況下為其新增功能)

2.返回值中包含函式名(不修改函式的呼叫方式)

import time

def timmer(func):

def warpper(*args,**kwargs):

start_time = time.time()

func()

stop_time = time.time()

print('time is %s' %(stop_time-start_time))

return warpper()

@timmer

def test1():

time.sleep(3)

print('in the test1')

test1()

''''''------高階函式1------

import time

def bar():

print('in the bar')

def test1(func):

start_time = time.time()

func() #run bar

stop_time = time.time()

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

test1(bar)

--------------高階函式2---------------------

import time

def bar():

time.sleep(3)

print('in the bar')

def test2(func):

print(func)

return func

print(test2(bar))

bar()

---------------巢狀函式-------------

def foo():

print('in the bar')

def bar():

print('in the bar')

bar()

foo()

x =0

def grandpa():

x=1def daa():

x=2def son():

x=3print(x)

son()

daa()

grandpa()

'''#裝飾器(需求:在不修改**的情況下給test1增加乙個功能)

import time

def timer(func):

def deco():

start_time = time.time()

func()

stop_time = time.time()

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

return deco

@timer #就等於 test1=timer(test1) 哪個函式使用新功能就寫在哪個函式上面

def test1():

time.sleep(3)

print('in the test1')

@timer

def test2():

time.sleep(3)

print('in the test2')

test1()

test2()

---------裝飾器案例----------------

import time

user,passwd = 'sun','123'

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("\033[32;1muser has passed authentication\033[0m")

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

print("---after authenticaion ")

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

def bbs():

print("welcome to bbs page")

index()

bbs()

python裝飾器介紹 Python之裝飾器簡介

python函式式程式設計之裝飾器 1.開放封閉原則 簡單來說,就是對擴充套件開放,對修改封閉。在物件導向的程式設計方式中,經常會定義各種函式。乙個函式的使用分為定義階段和使用階段,乙個函式定義完成以後,可能會在很多位置被呼叫。這意味著如果函式的定義階段 被修改,受到影響的地方就會有很多,此時很容易...

python 找到裝飾器 Python之裝飾器

裝飾器本質上就是乙個python函式,他可以讓其他函式在不需要做任何 變動的前提下,增加額外的功能,裝飾器的返回值也是乙個函式物件。裝飾器的作用 在不改變原函式及原函式的執行的情況下,為原函式增加一些額外的功能,比如列印日誌 執行時間,登入認證等等。乙個簡單的裝飾器 import time def ...

python 基礎裝飾器入門

1 裝飾器語法糖 python提供了 符號作為裝飾器的語法糖,使我們更方便的應用裝飾函式。但使用語法糖要求裝飾函式必須return乙個函式物件。因此我們將上面的func函式使用內嵌函式包裹並return。裝飾器相當於執行了裝飾函式use loggin後又返回被裝飾函式bar,因此bar 被呼叫的時候...