python 装饰器@及带参数的情况

一般装饰器:

def use_logging(func):
    def wrapper(*args, **kwargs):
        if level == 'warn':
            logging.warn('%s is running' % func.__name__)
        return func(*args)
    return wrapper

@use_logging
def foo(name = 'foo'):
    print ('i am %s' % name)

foo()

相当于

@use_logging 相当于
foo = use_logging(foo) foo 指向了 return 的wrapper,
foo()相当于 wrapper(),直接运行了wrapper里的内容以及func(*args)即def foo(name = 'foo')里的内容。
所以运行的时候def的foo(name='foo')都在上面装饰器中执行了,和下面的def foo没什么关系。

带参数装饰器:

import logging
def use_logging(level):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if level == 'warn':
                logging.warn('%s is running' % func.__name__)
            return func(*args)
        return wrapper
    return decorator

@use_logging(level = 'warn')
def foo(name = 'foo'):
    print ('i am %s' % name)

foo()

@use_logging(level = 'warn')相当于 use_logging(level = 'warn')(foo)就相当于返回的decorator(foo),即foo = decorator(foo),其余思路与上相同。

测试代码:

import logging
def use_logging(level):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if level == 'warn':
                logging.warn('%s is running' % func.__name__)
            return func(*args)
        return wrapper
    return decorator

@use_logging(level = 'warn')
def foo(name = 'foo'):
    print ('i am %s' % name)

foo()
WARNING:root:foo is running


i am foo
def foo2(name = 'foo2'):
    print ('i am %s' % name)   
#a = decorator
a = use_logging('warn')

#wrapper = decorator(foo2)
#wrapper('111'),执行代码,最后return foo('111)
print a(foo2)('222')    
#同理             
print a(foo2)('111') 
WARNING:root:foo2 is running
WARNING:root:foo2 is running


i am 222
None
i am 111
None

你可能感兴趣的:(python)