【发布时间】:2013-01-25 23:53:09
【问题描述】:
参考文献
在写这个问题之前,我参考了以下一些有趣的问题,感觉这个场景没有解释/涵盖:
- How to make a chain of function decorators?(特别是答案#2)
- How to decorate a method inside a class?
- Python decorators in classes
- Python Class Based Decorator with parameters that can decorate a method or a function(接近但不完全是我的要求)
我有一个function,如下:
def simple_function():
print 'this is a simple_function'
而且,我有以下class 和一些methods
class Test:
def Test_method_1(self, func, args=None, kwargs=None):
print 'this is Test::Test_method_1'
<execute some instructions here>
def Test_method_2(self):
print 'this is Test::Test_method_2'
我使用Test_method_1和simple_function如下:
t = Test()
t.Test_method_1(simple_function)
如果simple_function 接受任意参数,那么Test_method_1 的调用方式如下:
def simple_function(a, b, c, d=f, g=h):
print 'this is a simple_function'
t = Test()
t.Test_method_1(simple_function, args=[a, b, c], kwargs={d:f, g:h})
现在,我想使用Test_method_2 作为decorator version 的Test_method_1。所以simple_function的定义可以写成如下:
t = Test()
@t.Test_method_2
def simple_function():
print 'this is a simple_function'
注意:Test_method_2 将使用适当的参数调用 Test_method_1。
现在的问题:
- 1 - 这可能吗?
- 2 - 如果可能,如何将修饰函数的名称(此处为
simple_function)作为参数传递给Test_method_2(包括self)? - 3 - [这是杀手问题,我相信] 我想将任意参数传递给
Test_method_2(装饰器)和simple_function(被装饰的函数) -*args and **kwargs- @987654349 应该如何@被定义为接收参数(包括self)?
Test_method_2 用作 simple_function 的装饰器,两者都具有任意参数,如下所示:
t = Test()
@t.Test_method_2(a, b, c, d, e=f, g=h)
def simple_function(x, y, z, n=m):
print 'this is a simple_function'
【问题讨论】:
-
这就是
flask对@app.route('/path')所做的事情,所以这是可能的,我对lxml做了类似的事情,方法是装饰一个在Xpath 匹配时将被调用的函数,比如@ 987654357@ -
你试过了吗?您为什么不尝试一下,看看它是否有效,然后询问哪些无效的问题?
标签: python function methods decorator python-decorators