my_fun = decorate(my_fun)
,將 decorate()
指定(=
)給 my_fun
,因此 my_fun
會是經過 decorate()
包裝修飾過的版本@
符號來當做 decorator 所使用的語法糖符號,用來取代 my_fun = decorate(my_fun)
decorator 語法 (from 彭彭)
# decorator 語法
def decorator_fun(callback):
def fun_name():
# decorator code
# result 為參數,非必要
result = "dec"
print(result)
callback(result)
return fun_name
# 使用 @decorator_fun
@decorator_fun
def test(result):
# code
print("fun", result)
# 若無使用 decorator
# test = decorator_fun(test)
test()
# dec
# fun dec
decorator 語法 (from steam)
def a(func):
def c(m):
# decorator code
# m 為參數,非必要
print("decorator", m)
return func(m)
return c
@a
def b(msg):
# code
print(msg)
b("fun")
# decorator fun
# fun
來談談 generator(產生器)