欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python新手學習裝飾器

 更新時間:2020年06月04日 08:17:28   作者:愛喝馬黛茶的安東尼  
在本篇文章里小編給大家整理的是一篇關于Python裝飾器的相關知識點內(nèi)容,需要的朋友們可以學習下。

python函數(shù)式編程之裝飾器

1.開放封閉原則

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

在面向?qū)ο蟮木幊谭绞街?,?jīng)常會定義各種函數(shù)。一個函數(shù)的使用分為定義階段和使用階段,一個函數(shù)定義完成以后,可能會在很多位置被調(diào)用。這意味著如果函數(shù)的定義階段代碼被修改,受到影響的地方就會有很多,此時很容易因為一個小地方的修改而影響整套系統(tǒng)的崩潰,所以對于現(xiàn)代程序開發(fā)行業(yè)來說,一套系統(tǒng)一旦上線,系統(tǒng)的源代碼就一定不能夠再改動了。然而一套系統(tǒng)上線以后,隨著用戶數(shù)量的不斷增加,一定會為一套系統(tǒng)擴展添加新的功能。

此時,又不能修改原有系統(tǒng)的源代碼,又要為原有系統(tǒng)開發(fā)增加新功能,這就是程序開發(fā)行業(yè)的開放封閉原則,這時就要用到裝飾器了。

2.什么是裝飾器

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

所以裝飾器可以是任意可調(diào)用的對象,被裝飾的對象也可以是任意可調(diào)用對象。

3.裝飾器的作用

在不修改被裝飾對象的源代碼以及調(diào)用方式的前提下為被裝飾對象添加新功能。

原則:

1.不修改被裝飾對象的源代碼

2.不修改被裝飾對象的調(diào)用方式

目標:

為被裝飾對象添加新功能。

實例擴展:

import time
# 裝飾器函數(shù)
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
# 被裝飾函數(shù)1
@wrapper
def test1():
 time.sleep(1)
 print("in the test1")
# 被裝飾函數(shù)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)
# 調(diào)用
test1()
test2("Hello World")

不含參數(shù)實例:

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之裝飾器簡介內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論