python学习-装饰器(decorator)
生活随笔
收集整理的這篇文章主要介紹了
python学习-装饰器(decorator)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 裝飾器
- 普通裝飾器
- 裝飾器帶參數
- 類裝飾器
- 類方法裝飾器
裝飾器
裝飾器(Decorators)是 Python 的一個重要部分。簡單地說:他們是修改其他函數的功能的函數。
普通裝飾器
個人理解普通裝飾器和直接調用函數沒什么區別,就是相當于函數的調用。
def test1(x):return x ** 2def test2(x):return x * 3 + x / 2test1(6) test2(8)def func(f):def fNew(x):print(f.__name__)return f(x)return fNewf = func(test1) print(f(4))f = func(test2) print(f(4))@func def test3(x):return x * 10 * (x + 1)rst = test3(6) print(rst)from functools import wrapsdef a_new_decorator(a_func):@wraps(a_func)def wrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunction@a_new_decorator def a_function_requiring_decoration():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")print(a_function_requiring_decoration.__name__) a_function_requiring_decoration()運行結果:
大家可以自己運行一下。
裝飾器帶參數
裝飾器帶參數
類裝飾器
類裝飾器
類方法裝飾器
類方法裝飾器
后面的幾個內容,在這篇博文里面都已經有具體的代碼了,我這里就不再貼代碼了。
感興趣的小伙伴可以去看看。
python裝飾器相當于函數的調用
劃重點:
本文中鏈接都指向同一篇博文,所以點擊哪一個鏈接都可以噢。
總結
以上是生活随笔為你收集整理的python学习-装饰器(decorator)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python学习-列表解析、字典解析
- 下一篇: 捕捉画面中的相似元素可以让照片更有趣味性