python 裝飾器小白學習

解明月發表於2018-05-28

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)

相關文章