Python中decorator的使用(@函数的使用)
来源:互联网 发布:java的数据结构和算法 编辑:程序博客网 时间:2024/05/22 05:16
使用在Python 2.4 or Later.
两种调用形式:
1.不带参数
@A
def f():
def f():
Python最后会处理为:
f = A(f)
,可扩展为:
@A
@B
@C
def f():
@B
@C
def f():
最终Python会处理为:
f = A(B(C(f)))
2.带参数:
@A(args)
def f():
def f():
Python会处理为:
def f();
_deco = A(args)
f = _deco(f)
_deco = A(args)
f = _deco(f)
Python先执行A(args)得到_deco,然后跟第一种方式一样的处理函数f。
对应的两种函数定义方法:
第一种:
def A(func):
#处理func
#如func.attr='decorated'
return func
@A
def f(args): pass
#处理func
#如func.attr='decorated'
return func
@A
def f(args): pass
A对f处理完后,仍返回函数对象。 如果要返回一个新的函数,可以为:
def A(func):
#做额外的工作
def new_func(args):
#做额外工作
return func(args)
return new_func
@A
def f(args): pass
#做额外的工作
def new_func(args):
#做额外工作
return func(args)
return new_func
@A
def f(args): pass
注意:new_func的定义形式要和待处理的函数相同。
如果想根据原来函数的结果进行一些处理:
def A(func):
def new_func(*args, **argkw):
result = func(*args, **argkw)
if result:
return new_result
else:
return result
return new_func
@A
def f(args): pass
def new_func(*args, **argkw):
result = func(*args, **argkw)
if result:
return new_result
else:
return result
return new_func
@A
def f(args): pass
第二种:
def A(arg):
def _A(func):
def new_func(args):
#do any operation
return func(args)
return new_func
return _A
@A(arg)
def f(args): pass
def _A(func):
def new_func(args):
#do any operation
return func(args)
return new_func
return _A
@A(arg)
def f(args): pass
文档上说:如果你的decorator在调用时使用了参数,那么你的decorator函数只会使用这些参数进行调用。因此你需要返回一个新的decorator函数,就和第一种方式定义形式一致了。
- Python中decorator的使用(@函数的使用)
- Python:decorator的使用
- Python的decorator使用
- displaytag中decorator的使用原理
- decorator的使用
- python中函数的使用
- Python中函数的使用
- python中函数的使用
- Python中函数的使用
- Python的walk和Decorator使用一例
- Kivy A to Z -- Python Decorator的使用
- Python多个Decorator装饰器的使用
- siteMesh之decorator的使用
- flask中拦截用户登录修饰符decorator的使用
- python中map()函数的使用
- Python中set函数的使用
- python中自定义函数的使用
- Python中lambda匿名函数的使用
- 比自考更好的出路是什么?
- C#编码标准--编码习惯
- 增强安全性、支持跨页逻辑关系设定的电信运营级EnableQ在线问卷调查引擎V1.60来了...
- symbian下的文件操作
- 在EnableQ中定义逻辑关系
- Python中decorator的使用(@函数的使用)
- ASP.NET中防止刷新页面造成表单重复提交
- C# Observer模式
- c#中分割字符串的几种方法
- lucence实现中文检索(建立索引)
- C#实现快捷键 (系统热键)响应
- ucos邮箱之一
- Lucence Resource
- c#中什么情况下用(int)什么情况下用Convert.ToInt32