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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

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

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

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

比如說A現(xiàn)在已經(jīng)寫好了一個(gè)項(xiàng)目,但是現(xiàn)在B接管了這個(gè)項(xiàng)目,B需要對(duì)項(xiàng)目中的某個(gè)函數(shù)進(jìn)行修改,一個(gè)一個(gè)修改然后復(fù)制,粘貼?這時(shí)候修飾器就開始大顯身手了。修飾器可以避免許多重復(fù)的動(dòng)作。用@+修飾函數(shù)放在待修飾的函數(shù)頭上就可以實(shí)現(xiàn)優(yōu)化函數(shù)的功能

### 修飾器的理解

####原函數(shù)沒有參數(shù)

修飾器可以看作是一個(gè)接收函數(shù)的函數(shù),內(nèi)部再定義局部函數(shù)用來修飾傳進(jìn)來的函數(shù)參數(shù)

```

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

####原函數(shù)有參數(shù)

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

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

####類修飾器

大體上和函數(shù)修飾器差不多,只是類不能直接調(diào)用要加上__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

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。