from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print func.__name__ + " was called"
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print f.__name__# prints 'f'
print f.__doc__# prints 'does some math'
内置装饰器
@staticmathod、@classmethod、@property
装饰器的顺序
@a
@b
@c
def f ():
等效于
f = a(b(c(f)))
编辑于 2016-08-09
8 条评论
感谢
分享
收藏
?
没有帮助
?
举报
?
作者保留权利
收起
4
赞同
反对,不会显示你的姓名
许多人选择编程是因为他们喜欢把时间花在…
4 人赞同
先理解一下闭包的概念吧,之前回答过一个有关闭包和装饰器的问题,可以参考一下:Python 里函数里返回一个函数内部定义的函数? - 知乎用户的回答
显示全部
先理解一下闭包的概念吧 , 之前回答过一个有关闭包和装饰器的问题,可以参考一下:
Python 里函数里返回一个函数内部定义的函数? - 知乎用户的回答
发布于 2014-12-09
2 条评论
感谢
分享
收藏
?
没有帮助
?
举报
?
作者保留权利
1
赞同
反对,不会显示你的姓名
关于python修饰器调用报错问题你装饰器的用法不对,你要的功能大概的写法如下:
====
def tsfun(func, *args, **kwargs):
print "%s,%s, called" %(ctime(),func.__name__)
func(*args, **kwargs)
python中修饰器是什么?就是一个callable object 。它使python编程更加容易 。
例如:
@dec
def A(args):
pass
它就等价于dec(A). 当然还有带参数的decorator 。我就不举例了 。
python文档里有这样一句话 。
A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion.
大概就是说函数的定义可以用多个decorator 。decorator就在函数定义时用函数作为参数调用,然后返回一个可调用对象 。所以写decorator的时候一定要返回一个可调用对象 。
不知道你明白没 。
python的函数修饰器的介绍就聊到这里吧 , 感谢你花时间阅读本站内容,更多关于、python的函数修饰器的信息别忘了在本站进行查找喔 。
- redis的热点数据缓存 redis热点数据切换
- 如何修改戴尔服务器的IP地址? 戴尔服务器ip地址怎么改
- mysql中ext
- 优惠券功能的业务流程设计图谱 优惠券redis处理
- redis通配符的使用
- redis是开发工具吗 redis的开发人是谁
- mongodb查询字符串字段包含 mongodb查询字段不为空
- mysql备份一个表的数据 备份一个mysql库
- mysql中删除记录的命令 mysql删除中继日志
- mysql 判断 mysql的判断语句
