1.  首页
  2.  博客
  3. Python 设计模式 decorator

Python 设计模式 decorator


Decorators:

Another common way to alter the way a function behaves is to “decorate” it with another function. This is also often called “wrapping” a function, as decorators are designed to execute additional code before or after the original function gets called. The key principle behind decorators is that they accept callables and return new callables. The function returned by the decorator is the one that will be executed when the decorated function is called later. Care must be taken to make sure that the original function isn’t lost in the process, as there wouldn’t be any way to get it back without reloading the module. Decorators can be applied in a number of ways, either to a function you’re defining directly or to a function that was defined elsewhere. As of Python 2.4, decorators on newly defined functions can use a special syntax. In previous versions of Python, a slightly different syntax is necessary, but the same code can be used in both cases; the only difference is the syntax used to apply the decorator to the intended function. 以上是原文,不作翻译了。 from 《Pro Django》CHAPTER 2

示例代码:

def decorate(func):
    print 'Decorating %s...' % func.__name__,
    def wrapped(*args, **kargs):
          print "Called wrapped function with args:", args
          return func(*args, **kargs)
    print 'done!'
    return wrapped

@decorate
def test(a, b):
      return a + b

if __name__ == 'main':
    test(13, 72)

#output
Called wrapped function with args: (13, 72)
85

评论 0