python装饰器
来源:互联网 发布:海洋cms自动采集插件 编辑:程序博客网 时间:2024/06/06 03:43
装饰器的语法以@开头,接着是装饰器函数的名字、可选参数。紧跟装饰器声明的是被装饰的函数和被装饰的函数的可选参数,如下:@decorator(de...
装饰器的语法以@开头,接着是装饰器函数的名字、可选参数。
紧跟装饰器声明的是被装饰的函数和被装饰的函数的可选参数,如下:
@decorator(dec_opt_args)
def func(func_args):
....
其实总体说起来,装饰器其实也就是一个函数,一个用来包装函数的函数,装饰器在函数声明完成的时候被调用,调用之后声明的函数被换成一个被装饰器装饰过后的函数。
如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def
deco(func):
...
return
func
@deco
def
foo():
print
'foo'
#-----------------------------------
#等价如下:
def
deco(func):
...
return
func
def
foo():
print
'foo'
foo
=
deco(foo)
如下例子:
def
deco1(func):
print
'ok'
return
func
@deco1
def
foo():
print
'foo'
foo()
#输出--------------
#ok
#foo
#------------------
如果不使用装饰器,则可如下:
1
2
3
4
5
6
7
8
9
10
11
12
def
deco1(func):
print
'ok'
return
func
def
foo():
print
'foo'
print
foo
#<function foo at 0x00AFE6F0>
foo
=
deco1(foo)
foo()
#输出--------------
#ok
#foo
#------------------
两者对比下,可发现使用装饰器是那么简便、灵活。特别是在企业级的开发上。
同时也可以多个装饰器重叠使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def
deco1(func):
print
'deco1'
return
func
def
deco2(func):
print
'deco2'
return
func
@deco1
@deco2
def
foo():
print
'foo'
foo()
#输出如下:-----------
#deco2
#deco1
#foo
#---------------------
等效于:
1
2
3
4
5
@deco1
@deco2
def
foo(arg):
pass
-
-
-
-
-
-
-
-
-
-
-
与下等效
-
-
-
-
-
-
-
-
-
-
foo
=
deco1(deco2(foo()))
二、有参、无参的装饰器
上面的例子基本上都是有参数的,无参数更为简单。
1、无参
@deco1
@deco2
def foo(arg):pass
---------------------
foo = deco1(deco2(foo()))
2、有参
@deco1(deco_arg)
@deco2
def foo(arg):pass
---------------------
foo = deco1(deco_arg)(deco2(foo()))
返回以函数作为参数的装饰器
三、用处
1、引用日志
2、增加计时逻辑来检测性能
3、给函数加入事务的能力
四、实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from
time
import
ctime,sleep
def
deco(func):
def
decoIn():
print
'[%s]:%s called'
%
(ctime(),func.__name__)
return
func
return
decoIn
@deco
def
foo():
pass
foo()
sleep(
4
)
for
i
in
range
(
2
):
sleep(
1
)
foo()
#输出如下:--------
#[Fri Jul 05 10:45:04 2013]:foo called
#[Fri Jul 05 10:45:09 2013]:foo called
#[Fri Jul 05 10:45:10 2013]:foo called
#------------------
0 0
- python装饰器装饰类
- [python]python装饰器
- Python装饰器学习
- Python装饰器
- python 装饰器
- Python装饰器
- python 装饰器 应用
- python 装饰器2
- Python装饰器学习
- python装饰器
- python装饰器
- python 装饰器入门
- python装饰器
- python装饰器
- python 装饰器'@'
- python装饰器
- Python装饰器详解
- python 装饰器
- 利用js进行表单验证:判断用户名和密码非空
- DecimalFormat用法
- 多线程与网络
- android:layout_weight新认识
- CSS常用属性和值
- python装饰器
- CSS常用属性速查表
- GO语言网络编程之TCP (v1)
- Android基础(五) Service全解析----看不见的Activity
- HTML中调用JavaScript的几种情况和规范写法
- 使AJAX异步验证用户名和密码
- HTML代码之爱心树表白
- 三种编程范式——函数式|过程式|OO
- Flask和@app.route(1)