看板 Python 關於我們 聯絡資訊
大家好,我想測試一下decorator的用法, 所以用以下兩個函數, def f1(value): return value + 1 @f1 #decorator def f2(): return 10 想做出f()的效果 def f3(): return 10 def f(): return f1(f3()) 可是卻出現error -- TypeError: unsupported operand type(s) for +: 'function' and 'int' 請問decorator的使用方式有什麼問題嗎? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.251.151.106
mikapauli:decorator應該是function to function 02/28 14:15
mikapauli:def _f1(v): 02/28 14:22
mikapauli: return v + 1 02/28 14:22
mikapauli:def f1(f): 02/28 14:23
mikapauli: def _f(): 02/28 14:23
mikapauli: return _f1(f()) 02/28 14:23
mikapauli: return _f 02/28 14:23
mikapauli:大概像這樣 02/28 14:24
beatitude:我後來改成: 02/28 17:21
beatitude:def test(f): 02/28 17:22
beatitude: print "test" 02/28 17:22
beatitude:@test #decorator 02/28 17:22
beatitude:def f(): 02/28 17:22
beatitude: print "@" 02/28 17:22
beatitude:f() 02/28 17:22
beatitude:結果出現錯誤訊息: 02/28 17:23
beatitude:TypeError: 'NoneType' object is not callable 02/28 17:23
ypcat:@foo 02/28 17:40
ypcat:def bar(): 02/28 17:40
ypcat: pass 02/28 17:40
ypcat:以上寫法等同於 bar=foo(bar) 02/28 17:43
ypcat:decorator 只是一種 syntatic sugar 沒什麼特別 02/28 17:44
ypcat:一般的用法是傳入一個 function 然後產生另一個 function 02/28 17:47
ypcat:像 mikapauli 舉的例子那樣 02/28 17:47
ypcat:打錯字 syntatic -> syntactic 02/28 17:49