python-Decorator

https://www.youtube.com/watch?v=qc8hsxAK270&list=PL-g0fdC5RMboYEyt6QS2iLb_1m7QcgfHk&index=34

定義裝飾器
def 定義裝飾器(回呼函式):
def 內部函式():
#裝飾器函式內碼
回呼函式名稱()
return 內部函式名稱

使用裝飾器
@裝飾器名稱
def 函式名稱():
#函式程式碼
函式名稱() #呼叫帶有裝飾器名稱

範例:
def testDecorator(callback):
def innerFunc():
callback()
return innerFunc

@testDecorator
def decoratedFunc():
print("普通函式")

defcoratedFunc()

===============
#定義裝飾器
def myDeco(cb):
def run():
print("1.裝飾器中的程式碼")
cb(5) #這回呼函式,其實是被裝式的函式 test
return run
#使用裝飾器
@myDeco #先執行裝飾器內程式碼
def test(n):
print("2.普通函式程式碼", n)

test()

##callback 範例
print("=======================================")
print("callback")
def add(n1, n2, db):
db(n1 + n2)

def handle(result):
print("sum:" , result)

def handle1(result):
print("english sum1:" , result)

add(10, 23, handle)
add(10, 23, handle1)

handle(10)

本篇發表於 python。將永久鍊結加入書籤。

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*

您可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>