學習整理--python裝飾器

來源:互聯網
上載者:User

標籤:標準   添加   war   int   *args   函數   等價   功能   return   

使用情境:

       思考這樣一個問題:對於生產系統,如何在修改最小,實現對原有模組添加新的功能呢?!通過裝飾器,即可完成這一目標。

  裝飾器有兩個標準:

    1、不修改原有代碼及原有調用方式;

    2、可以增加新的功能;

 

  例如,我們有一個方法func1,在這個方法中,列印兩條資訊並sleep 1秒鐘。

def func1():
print("this is in the func1 methord")
time.sleep(1)
print("exec the func1 finished")

‘‘‘調用方法‘‘‘
if __name__ == "__main__":
  func1()

  現在我想不修改func1()方法及其調用方式的前提下,增加一個列印目前時間的功能,如何?呢?

import time

def timmer(func):#定義裝飾器timmer
def decotator(*args,**kwargs):#定義高階函數
print("this is in the decorator,and current time is %s",args,kwargs)#添加的方法
func(*args,**kwargs)#執行傳遞變數的方法
return decotator#另其返回高階函數地址

@timmer#指明裝飾器為timmer,等價於func1=timmer(func1)
def func1():
print("this is in the func1 methord")
time.sleep(1)
print("exec the func1 finished")

@timmer
def func2(name):
print("this is in the func2 methord,and the name is :%s" %name)
time.sleep(1)
print("exec the func2 finished")



#調用func1方法
func1()

學習整理--python裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.