如何使用参数或不带参数编写支持调用的装饰器?

时间:2014-07-17 06:42:13

标签: python

我正在学习python中的装饰器。我想写一个可以打印"开始调用"在我打电话给func并打印"结束通话"在电话之后。这并不困难。 但现在我想改进这个装饰器。我希望它不仅支持这样的用法:

@deco
def func():
    pass

但也支持这样的用法:

@deco("execute")
def func()
    pass

我已经写过代码:

def deco(text=None):
    if isinstance(text, str) or text == None:
        def _deco(func):
            def __deco(*args, **kw):
                print "%s call:" % text
                ret = func(*args, **kw)
                print "end call"
                return ret
            return __deco
        return _deco
    else:
        def _deco(*args, **kw):
            print "begin call:"
            ret = text(*args, **kw)
            print "end call:"
            return ret
        return _deco

@deco
def hello():
    print "hello"

@deco("execute")
def newhello():
    print "newhello"

并且在第17行和第34行出现IdentationError;返回ret"。它说:unindent与任何外部缩进级别都不匹配。 你能告诉我如何纠正我的代码以满足我的需求吗?

1 个答案:

答案 0 :(得分:0)

带参数的装饰器的语法有点不同 - 带参数的装饰器应返回一个函数,该函数将接受一个函数并返回另一个函数。所以它应该真正返回一个普通的装饰器。我的意思是,你可以做这样的事情。

def decorator(argument):
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            function(*args, **kwargs)
            more_funny_stuff()
        return wrapper
     return real_decorator

Here您可以找到有关装饰器的更多信息。