Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python装饰参数_Python_Python 2.7_Python Decorators - Fatal编程技术网

python装饰参数

python装饰参数,python,python-2.7,python-decorators,Python,Python 2.7,Python Decorators,python decorator函数是否支持参数a实现如何 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):

python decorator函数是否支持参数a实现如何

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)或@decorator arg。但效果并不理想。到目前为止,我想知道这是否可能

我想你可能想要这样的东西:

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

我想你可能想要这样的东西:

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

是的,但您的示例似乎表明您不了解装饰师是如何工作的。例如,你读过吗?你想让你的装饰师做什么?你应该阅读这篇博文来更好地理解如何使用装饰师:是的,但是你的例子似乎表明你不了解装饰师是如何工作的。例如,你读过吗?你想让你的decorator做什么?你应该阅读这篇文章来更好地理解如何使用decorator:你也可以使用嵌套函数,而不是decorator类。唉,Python的缩进要求不允许我在这里的注释中键入示例。您也可以使用嵌套函数,而不是decorator类。唉,Python的缩进要求不允许我在注释中键入示例。