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

歡迎訪問 生活随笔!

生活随笔

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

python

python重写和装饰器_python中的装饰器

發布時間:2023/12/15 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python重写和装饰器_python中的装饰器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

裝飾器的本質:

當你在用某個@decorator來修飾某個函數func時,如下所示:

@decorator

def?func():

pass

其解釋器會解釋成下面這樣的語句:

func=decorator(func)

本質是把一個函數當作參數傳遞到另一個函數中,然后再調用。

def?hello(fn):

def?wrapper():

print?"hello,%s"?%fn.__name__

fn()

print?"goodbye,%s"?%fn.__name__

return?wrapper

@hello

def?foo():

print?"I?am?foo"

>>>foo()

"hello,foo"

"I?am?foo"

"goodbye,foo"

hello(foo)返回了wrapper()函數,所以foo其實變成了wrapper的一個變量,而后面的foo()執行其實變成了wrapper()

多個裝飾器:

@decorator_one

@decorator_two

def?func():

pass

相當于func=decorator_one(decorator_two(func))

帶參數的裝飾器:

@decorator(arg1,arg2)

def?func():

pass

相當于func=decorator(arg1,arg2)(func).這意味著decorator(arg1,arg2)這個函數需要返回一個“真正的裝飾器”。

def?mydecorator(arg1,arg2):

def?_mydecorator1(func):

def?_mydecorator2(*args,**kw):

res=func(*args,**kw)

return?res

return?_mydecorator2

return?_mydecorator1

上面的函數返回的_mydecorator1才是真正的裝飾器。因此,當裝飾器需要參數時,必須使用第二集封裝。因為裝飾器在模塊第一次被讀取時由解釋程序裝入,所以它們的使用必須受限于總體上可以應用的封裝器。

帶參數及多個裝飾器:

def?makeHtmlTag(tag,*args,**kwds):

def?real_decorator(fn):

css_class="class=‘{0}‘".format(kwds["css_class"])?if?"css_class"?in?kwds?else?""

def?wrapped(*args,**kwds):

return?""+fn(*args,**kwds)+""+tag+">"

return?warpped(*args,**kwds)

return?real_decorator

@makeHtmlTag(tag=‘i‘,css_class=‘italic_css‘)

@makeHtmlTag(tag=‘b‘,css_class=‘bold_css‘)

def?hello():

return?"hello?world"

>>>hello()

hello?world

class式裝飾器:

class?mydecorator(object):

def?__init__(self,fn):

print?"inside?mydecorator--init"

self.fn=fn

def?__call__(self):

self.fn()

print?"inside?mydecorator--call"

@mydecorator

def?myfunc():

print?"inside?myfunc"

>>>myfunc

"inside?mydecorator--init"

"inside?myfunc"

"inside?mydecorator--call"

重寫makeHtmlTag代碼:

原文:http://my.oschina.net/935572630/blog/393489

總結

以上是生活随笔為你收集整理的python重写和装饰器_python中的装饰器的全部內容,希望文章能夠幫你解決所遇到的問題。

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