日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3 修饰器_【python3】修饰器简单理解

發布時間:2025/3/15 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3 修饰器_【python3】修饰器简单理解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

### 修飾器干嘛的,有什么作用

比如說A現在已經寫好了一個項目,但是現在B接管了這個項目,B需要對項目中的某個函數進行修改,一個一個修改然后復制,粘貼?這時候修飾器就開始大顯身手了。修飾器可以避免許多重復的動作。用@+修飾函數放在待修飾的函數頭上就可以實現優化函數的功能

### 修飾器的理解

####原函數沒有參數

修飾器可以看作是一個接收函數的函數,內部再定義局部函數用來修飾傳進來的函數參數

```

def makebold(fn):

def wrapped():

return "" + fn() + ""

return wrapped

def makeitalic(fn):

def wrapped():

return "" + fn() + ""

return wrapped

@makebold

@makeitalic

def hello():

return "hello world"

print hello() ## 返回 hello world

####原函數有參數

修飾函數還是傳函數參數,修飾函數里面的局部函數傳入原函數的參數

def w2(fun):

def wrapper(args,**kwargs):

print("this is the wrapper head")

fun(args,**kwargs)

print("this is the wrapper end")

return wrapper

@w2

def hello(name,name2):

print("hello"+name+name2)

hello("world","!!!")

輸出:

this is the wrapper head

helloworld!!!

this is the wrapper end

####需要有返回值

def w3(fun):

def wrapper():

print("this is the wrapper head")

temp=fun()

print("this is the wrapper end")

return temp #要把值傳回去呀!!

return wrapper

@w3

def hello():

print("hello")

return "test"

result=hello()

print("After the wrapper,I accept %s" %result)

輸出:

this is the wrapper head

hello

this is the wrapper end

After the wrapper,I accept test

####類修飾器

大體上和函數修飾器差不多,只是類不能直接調用要加上__call__方法。

class Test(object):

def init(self, func):

print('test init')

print('func name is %s ' % func.name)

self.__func = func

def __call__(self, *args, **kwargs):

print('this is wrapper')

self.__func()

@Test

def test():

print('this is test func')

test()

輸出:

test init

func name is test

this is wrapper

this is test func

總結

以上是生活随笔為你收集整理的python3 修饰器_【python3】修饰器简单理解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。