裝飾器是由函數(shù)去生成的,用于裝飾某個(gè)函數(shù)或者方法或者類,他可以讓這個(gè)函數(shù)在執(zhí)行之前或者執(zhí)行之后做一些操作。
先定義一個(gè)函數(shù)func
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
def func(arg): # 接受一個(gè)參數(shù)arg
print(arg) # 輸出這個(gè)參數(shù)
func("Hello World!") # 調(diào)用腳本并且傳入?yún)?shù)
執(zhí)行腳本,輸出的結(jié)果為:
C:\Python35\python.exe F:/Python_code/Note/裝飾器.py
Hello World!
Process finished with exit code 0
現(xiàn)要在執(zhí)行func這個(gè)函數(shù)前后執(zhí)行一些操作,就可以創(chuàng)建一個(gè)裝飾器來(lái)實(shí)現(xiàn):
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
def decorator(func): # 創(chuàng)建一個(gè)裝飾器函數(shù),接受的參數(shù)arg參數(shù)就是func函數(shù)名
def inner(*args, **kwargs):
print("執(zhí)行函數(shù)之前")
ret = func(*args, **kwargs)
print("執(zhí)行函數(shù)之后")
return ret
return inner
@decorator # 如果要讓某個(gè)函數(shù)使用裝飾器,只需要在這個(gè)函數(shù)上面加上@+裝飾器名
def func(arg):
print(arg)
func("Hello World!")
輸出結(jié)果為:
/usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/裝飾器.py
執(zhí)行函數(shù)之前
Hello World!
執(zhí)行函數(shù)之后
Process finished with exit code 0
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
def decorator1(func):
def inner():
print("開始之前執(zhí)行裝飾器01")
ret = func()
print("結(jié)束之后執(zhí)行裝飾器01")
return ret
return inner
def decorator2(func):
def inner():
print("decorator2>>>Start...")
ret = func()
print("decorator2>>>End...")
return ret
return inner
@decorator1
@decorator2
def index():
print("執(zhí)行函數(shù)...")
index()
輸出結(jié)果:
/usr/bin/python3.5 /home/ansheng/Documents/PycharmProjects/blogcodes/裝飾器.py
開始之前執(zhí)行裝飾器01
decorator2>>>Start...
執(zhí)行函數(shù)...
decorator2>>>End...
結(jié)束之后執(zhí)行裝飾器01
Process finished with exit code 0
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# Created by 安生 on 2017/2/9
"""
函數(shù)裝飾器
"""
def decorator(func):
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
return wrapped
@decorator
def func(a, b):
return a + b
print(func(1, 2))
"""
類裝飾器
"""
class decorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
@decorator
def func(a, b):
return a + b
print(func(1, 2))
"""
帶參數(shù)的函數(shù)裝飾器
"""
def parameter(a, b):
print(a, b)
def decorator(func):
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
return wrapped
return decorator
@parameter(1, 2)
def func(a, b):
return a + b
print(func(10, 20))
"""
帶參數(shù)的類裝飾器
"""
def parameter(a, b):
print(a + b)
class decorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
return decorator
@parameter(1, 2)
def func(a, b):
return a + b
print(func(10, 20))
"""
帶參數(shù)的類裝飾器
"""
def parameter(a, b):
print(a, b)
def decorator(cls):
class wrapped:
def __init__(self, *args, **kwargs):
self.cls = cls(*args, **kwargs)
def __getattr__(self, item):
return getattr(self.cls, item)
return wrapped
return decorator
@parameter(1, 2)
class CLS:
def __init__(self):
self.a = 'a'
def P(self, v):
print(v)
obj = CLS()
print(obj.a)
obj.P('Hello,')
"""
為函數(shù)中和類中的方法添加裝飾器
"""
def Call(aClass):
calls = 0
def onCall(*args, **kwargs):
nonlocal calls
calls += 1
print('call %s to %s' % (calls, func.__name__))
return aClass(*args, **kwargs)
return onCall
@Call
def func(a, b):
return a + b
print(func(1, 2))
class CLS:
def __init__(self):
self.a = 'a'
@Call
def b(self):
return self.a
obj = CLS()
print(obj.b())
本文出自 “一盞燭光” 博客,謝絕轉(zhuǎn)載!
更多建議: