python 装饰器小白学习

python装饰器

import functools
def use_log_src(func):
    print 'log src'
    func()

def use_log(func):
    def wrapper(*args, **kwargs):
        print 'log log'
        return func(*args, **kwargs)
    return wrapper

def bar():
    print 'i am bar'

@use_log
def barnew():
    print 'i am bar new'

@use_log
def foonew():
    print 'i am foo new'

def use_log_args(level):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if level == 'warn':
                print 'log wrapper'
            return func(*args, **kwargs)
        return wrapper
    return decorator

@use_log_args(level='warn')
def foobest(name='foobest'):
    print 'name is %s' % name

class Foo(object):
    def __init__(self, func):
        self._func = func

    def __call__(self):
        print 'start'
        self._func()
        print 'end'
@Foo
def barClass():
    print 'bar class'

def logged(func):
    @functools.wraps(func)
    def with_log(*args, **kwargs):
        print func.__name__ + 'was called'
        return func(*args, **kwargs)
    return with_log

@logged
def f(x):
    return x + x * x


# 1 想要在bar上添加一句日志
#use_log_src(bar)

# 2 简单的装饰器
#bar = use_log(bar)
#bar()

# 3 装饰器之小白语法糖使用
#barnew()
#foonew()

# 4 带参数的装饰器
#foobest()

# 5 类装饰器
# barClass()

# 6 通过functools.wraps将原来的函数元信息拷贝过去
print f(10)

你可能感兴趣的:(python学习)