2013-03-02 95 views
0

待办事项蟒蛇装饰功能的支持参数的是如何实施蟒蛇装饰参数

def decorator(fn, decorArg): 
    print "I'm decorating!" 
    print decorArg 
    return fn 

class MyClass(object): 
    def __init__(self): 
     self.list = [] 

    @decorator 
    def my_function(self, funcArg = None): 
     print "Hi" 
     print funcArg 

上来看,我得到这个错误

TypeError: decorator() takes exactly 2 arguments (1 given) 

我试过@decorator(ARG)或@装饰ARG 。它没有工作。到目前为止,我不知道这是可能的

+1

是的,但你的例子似乎表明你不明白装饰者是如何工作的。例如,你读过[this](http://www.python.org/dev/peps/pep-0318/#current-syntax)吗?你想让你的装饰者做什么? – BrenBarn 2013-03-02 06:36:54

+1

你应该阅读这篇文章,以更好地了解如何使用装饰器:http://stackoverflow.com/questions/739654/understanding-python-decorators – 2013-03-02 06:41:40

回答

3

我想你可能想是这样的:

class decorator: 
    def __init__ (self, decorArg): 
     self.arg = decorArg 

    def __call__ (self, fn): 
     print "I'm decoratin!" 
     print self.arg 
     return fn 

class MyClass (object): 
    def __init__ (self): 
     self.list = [] 

    @decorator ("foo") 
    def my_function (self, funcArg = None): 
     print "Hi" 
     print funcArg 

MyClass().my_function ("bar") 

或者嵌套功能BlackNight指出:

def decorator (decorArg): 
    def f (fn): 
     print "I'm decoratin!" 
     print decorArg 
     return fn 
    return f 
+0

你也可以使用嵌套函数,而不是装饰器类。唉,Python的缩进要求不允许我在评论中输入示例。 – Blckknght 2013-03-02 07:14:23