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裝飾器(decorator)學習Python
- Python學習筆記 - 裝飾器Python筆記
- 【python學習筆記】Python裝飾器Python筆記
- python基礎學習12—-裝飾器Python
- 裝飾器學習筆記筆記
- Python 中級學習之函式裝飾器Python函式
- 草根學Python(十六) 裝飾器(逐步演化成裝飾器)Python
- 初學 Python(十五)——裝飾器Python
- python裝飾器2:類裝飾器Python
- Python裝飾器探究——裝飾器引數Python
- Python 裝飾器初學筆記Python筆記
- 從零開始的Python學習Episode 11——裝飾器Python
- Python 裝飾器Python
- Python裝飾器Python
- 裝飾器 pythonPython
- Python學習之路26-函式裝飾器和閉包Python函式
- Python學習之三大名器-裝飾器、迭代器、生成器Python
- Python 裝飾器裝飾類中的方法Python
- Python裝飾器模式Python模式
- python的裝飾器Python
- 1.5.3 Python裝飾器Python
- Python 裝飾器(一)Python
- Python 裝飾器原理Python
- Python零基礎學習筆記(二十五)——裝飾器Python筆記
- 裝飾者模式學習模式
- 學習 ES7 語法 decorator 裝飾器
- 設計模式學習筆記(3)裝飾器設計模式筆記
- python 之裝飾器(decorator)Python
- Python深入05 裝飾器Python
- Python裝飾器詳解Python
- Python中的裝飾器Python
- 【Python】淺談裝飾器Python
- 初識Python裝飾器Python
- Python 裝飾器的理解Python
- python裝飾器介紹Python
- 淺談Python裝飾器Python
- 5個理由告訴你為什麼要學習使用Python裝飾器Python
- Python3 裝飾器解析Python