作者beatitude (...)
站内Python
标题[问题] decorator的用法
时间Tue Feb 28 13:35:35 2012
大家好,我想测试一下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
1F:推 mikapauli:decorator应该是function to function 02/28 14:15
2F:推 mikapauli:def _f1(v): 02/28 14:22
3F:→ mikapauli: return v + 1 02/28 14:22
4F:→ mikapauli:def f1(f): 02/28 14:23
5F:→ mikapauli: def _f(): 02/28 14:23
6F:→ mikapauli: return _f1(f()) 02/28 14:23
7F:→ mikapauli: return _f 02/28 14:23
8F:→ mikapauli:大概像这样 02/28 14:24
9F:→ beatitude:我後来改成: 02/28 17:21
10F:→ beatitude:def test(f): 02/28 17:22
11F:→ beatitude: print "test" 02/28 17:22
13F:→ beatitude:def f(): 02/28 17:22
14F:→ beatitude: print "@" 02/28 17:22
15F:→ beatitude:f() 02/28 17:22
16F:→ beatitude:结果出现错误讯息: 02/28 17:23
17F:→ beatitude:TypeError: 'NoneType' object is not callable 02/28 17:23
18F:推 ypcat:@foo 02/28 17:40
19F:→ ypcat:def bar(): 02/28 17:40
20F:→ ypcat: pass 02/28 17:40
21F:→ ypcat:以上写法等同於 bar=foo(bar) 02/28 17:43
22F:→ ypcat:decorator 只是一种 syntatic sugar 没什麽特别 02/28 17:44
23F:→ ypcat:一般的用法是传入一个 function 然後产生另一个 function 02/28 17:47
24F:→ ypcat:像 mikapauli 举的例子那样 02/28 17:47
25F:→ ypcat:打错字 syntatic -> syntactic 02/28 17:49