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學習筆記 - 裝飾器Python筆記
- python基礎學習12—-裝飾器Python
- Python 中級學習之函式裝飾器Python函式
- python裝飾器2:類裝飾器Python
- 裝飾器學習筆記筆記
- Python 裝飾器初學筆記Python筆記
- Python 裝飾器Python
- Python裝飾器Python
- 從零開始的Python學習Episode 11——裝飾器Python
- Python學習之路26-函式裝飾器和閉包Python函式
- 1.5.3 Python裝飾器Python
- Python 裝飾器(一)Python
- python的裝飾器Python
- Python 裝飾器原理Python
- Python裝飾器模式Python模式
- Python學習之三大名器-裝飾器、迭代器、生成器Python
- Python零基礎學習筆記(二十五)——裝飾器Python筆記
- Python深入05 裝飾器Python
- python 之裝飾器(decorator)Python
- Python中的裝飾器Python
- Python裝飾器詳解Python
- 設計模式學習筆記(3)裝飾器設計模式筆記
- 學習 ES7 語法 decorator 裝飾器
- python裝飾器入門探究Python
- python 裝飾器 part2Python
- day11(python)裝飾器Python
- python中裝飾器的原理Python
- Python裝飾器高階用法Python
- 【python】閉包與裝飾器Python
- Python裝飾器的前世今生Python
- python的裝飾器@的用法Python
- Python深入分享之裝飾器Python
- Python 語法之裝飾器Python
- Python3 裝飾器解析Python
- Python閉包與裝飾器Python
- Python之函式裝飾器Python函式
- Python 裝飾器簡單示例Python
- python裝飾器有哪些作用Python