1
2
3
|
class
MyClass(
object
):
def
staticFoo():
staticFoo
=
staticmethod
(staticFoo)
|
1
2
3
4
|
class
MyClass(
object
):
@
staticmethod
def
staticFoo():
pass
|
-
一个装饰器
1
2
3
|
@f
def
foo():
pass
|
1
2
3
|
def
foo():
pass
foo
=
g(foo)
|
-
多个装饰器
1
2
3
4
|
@g
@f
def
foo():
pass
|
1
2
3
|
def
foo():
pass
foo
=
g(f(foo))
|
-
带有参数的一个装饰器
1
2
3
|
@decomaker
(deco_args)
def
foo():
pass
|
1
2
3
|
def
foo():
pass
foo
=
decomaker(deco_args)(foo)
|
-
带有参数的多个装饰器
1
2
3
4
|
@deco1
(deco_arg)
@deco2
()
def
foo():
pass
|
1
2
3
|
def
foo():
pass
foo
=
deco1(deco_arg)(deco2(foo))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
from
functools
import
wraps
def
log(text):
def
decorator(func):
@wraps(func)
#it works like:wraper.__name__ = func.__name__
def
wrapper(
*
args,
*
*
kwargs):
print
'%s %s():'
%
(text, func.__name__)
return
func(
*
args,
*
*
kwargs)
return
wrapper
return
decorator
@log
(
'Hello'
)
def
now(area):
print
area,
'2016-01-23'
now(
'Beijing'
)
print
'The name of function now() is:'
, now.__name__
|
1
2
3
4
|
/
usr
/
bin
/
python2.
7
/
home
/
xpleaf
/
PycharmProjects
/
decorator_test
/
dec10.py
Hello now():
Beijing
2016
-
01
-
23
The name of function now()
is
: now
|
|
1
|
wraper.__name__
=
func.__name__
|