python wraps decorator
来源:互联网 发布:网络的危害 编辑:程序博客网 时间:2024/06/16 16:42
from
inspect
import
getmembers, getargspec
from
functools
import
wraps
def
wraps_decorator(f):
@wraps
(f)
def
wraps_wrapper(
*
args,
*
*
kwargs):
return
f(
*
args,
*
*
kwargs)
return
wraps_wrapper
class
SomeClass(
object
):
@wraps_decorator
def
method(
self
, x, y):
pass
obj
=
SomeClass()
for
name, func
in
getmembers(obj, predicate
=
inspect.ismethod):
print
"Member Name: %s"
%
name
print
"Func Name: %s"
%
func.func_name
print
"Args: %s"
%
getargspec(func)[
0
]
class
myDecorator(
object
):
def
__init__(
self
, fn):
print
"inside myDecorator.__init__()"
self
.fn
=
fn
def
__call__(
self
):
self
.fn()
print
"inside myDecorator.__call__()"
@myDecorator
def
aFunction():
print
"inside aFunction()"
print
"Finished decorating aFunction()"
aFunction()
你会发现,即使是你你用了functools的wraps,你在用getargspec时,参数也不见了。
要修正这一问,我们还得用Python的反射来解决,下面是相关的代码:
1
2
3
4
5
6
7
8
9
10
11
12
def
get_true_argspec(method):
argspec
=
inspect.getargspec(method)
args
=
argspec[
0
]
if
args
and
args[
0
]
=
=
'self'
:
return
argspec
if
hasattr
(method,
'__func__'
):
method
=
method.__func__
if
not
hasattr
(method,
'func_closure'
)
or
method.func_closure
is
None
:
raise
Exception(
"No closure for method."
)
method
=
method.func_closure[
0
].cell_contents
return
get_true_argspec(method)
当然,我相信大多数人的程序都不会去getargspec。所以,用functools的wraps应该够用了。
class
MyApp():
def
__init__(
self
):
self
.func_map
=
{}
def
register(
self
, name):
def
func_wrapper(func):
self
.func_map[name]
=
func
return
func
return
func_wrapper
def
call_method(
self
, name
=
None
):
func
=
self
.func_map.get(name,
None
)
if
func
is
None
:
raise
Exception(
"No function registered against - "
+
str
(name))
return
func()
app
=
MyApp()
@app
.register(
'/'
)
def
main_page_func():
return
"This is the main page."
@app
.register(
'/next_page'
)
def
next_page_func():
return
"This is the next page."
print
app.call_method(
'/'
)
print
app.call_method(
'/next_page'
)
0 0
- python wraps decorator
- Python 入门:装饰器(decorator)、@functools.wraps、@staticmethod、@classmethod
- python 理解functools.wraps
- python中的wraps函数
- python @wraps修饰器
- tensorflow编程: Wraps python functions
- python装饰器的wraps作用
- 用Python functools.wraps实现装饰器
- 用Python functools.wraps实现装饰器
- Python 装饰器之 functools.wraps
- python装饰器的wraps作用
- python中functools.wraps的作用
- 简单聊聊Python中的wraps修饰器
- python decorator
- python decorator
- python decorator
- python decorator
- Python - Decorator
- 关于QQ通讯录的应用及vcf文件导入手机的乱码问题
- 谁考了第k名:Wrong Answer
- mongodb安全问题
- 乐队设备---均衡器的学习和使用
- 09 在ubuntu中切换多终端的方法
- python wraps decorator
- mysql数据库绿色版手工安装步骤
- tolua++的使用
- TZU2014年省赛个人热身赛1 1187:Do the Untwist
- java单向循环链表实现约瑟夫环
- 设置GVim的打开文件后自动最大化
- 最舒适的一刻
- 打开页面报错
- 经典杂录