1. 程式人生 > 程式設計 >Python新手學習裝飾器

Python新手學習裝飾器

python函數語言程式設計之裝飾器

1.開放封閉原則

簡單來說,就是對擴充套件開放,對修改封閉。

在面向物件的程式設計方式中,經常會定義各種函式。一個函式的使用分為定義階段和使用階段,一個函式定義完成以後,可能會在很多位置被呼叫。這意味著如果函式的定義階段程式碼被修改,受到影響的地方就會有很多,此時很容易因為一個小地方的修改而影響整套系統的崩潰,所以對於現代程式開發行業來說,一套系統一旦上線,系統的原始碼就一定不能夠再改動了。然而一套系統上線以後,隨著使用者數量的不斷增加,一定會為一套系統擴充套件新增新的功能。

此時,又不能修改原有系統的原始碼,又要為原有系統開發增加新功能,這就是程式開發行業的開放封閉原則,這時就要用到裝飾器了。

2.什麼是裝飾器

裝飾器,顧名思義,就是裝飾,修飾別的物件的一種工具。

所以裝飾器可以是任意可呼叫的物件,被裝飾的物件也可以是任意可呼叫物件。

3.裝飾器的作用

在不修改被裝飾物件的原始碼以及呼叫方式的前提下為被裝飾物件新增新功能。

原則:

1.不修改被裝飾物件的原始碼

2.不修改被裝飾物件的呼叫方式

目標:

為被裝飾物件新增新功能。

例項擴充套件:

import time
# 裝飾器函式
def wrapper(func):
 def done(*args,**kwargs):
  start_time = time.time()
  func(*args,**kwargs)
  stop_time = time.time()
  print('the func run time is %s' % (stop_time - start_time))
 return done
# 被裝飾函式1
@wrapper
def test1():
 time.sleep(1)
 print("in the test1")
# 被裝飾函式2
@wrapper
def test2(name): #1.test2===>wrapper(test2) 2.test2(name)==dome(name)
 time.sleep(2)
 print("in the test2,the arg is %s"%name)
# 呼叫
test1()
test2("Hello World")

不含引數例項:

import time
user,passwd = 'admin','admin'
def auth(auth_type):
 print("auth func:",auth_type)
 def outer_wrapper(func):
  def wrapper(*args,**kwargs):
   print("wrapper func args:",*args,**kwargs)
   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連結")
  return wrapper
 return outer_wrapper
@auth(auth_type="local") # home = wrapper()
def home():
 print("welcome to home page")
 return "from home"
@auth(auth_type="ldap")
def bbs():
 print("welcome to bbs page"
print(home()) #wrapper()
bbs()

到此這篇關於Python新手學習裝飾器的文章就介紹到這了,更多相關Python之裝飾器簡介內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!