python重写和装饰器_python中的装饰器
裝飾器的本質(zhì):
當(dāng)你在用某個(gè)@decorator來(lái)修飾某個(gè)函數(shù)func時(shí),如下所示:
@decorator
def?func():
pass
其解釋器會(huì)解釋成下面這樣的語(yǔ)句:
func=decorator(func)
本質(zhì)是把一個(gè)函數(shù)當(dāng)作參數(shù)傳遞到另一個(gè)函數(shù)中,然后再調(diào)用。
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()函數(shù),所以foo其實(shí)變成了wrapper的一個(gè)變量,而后面的foo()執(zhí)行其實(shí)變成了wrapper()
多個(gè)裝飾器:
@decorator_one
@decorator_two
def?func():
pass
相當(dāng)于func=decorator_one(decorator_two(func))
帶參數(shù)的裝飾器:
@decorator(arg1,arg2)
def?func():
pass
相當(dāng)于func=decorator(arg1,arg2)(func).這意味著decorator(arg1,arg2)這個(gè)函數(shù)需要返回一個(gè)“真正的裝飾器”。
def?mydecorator(arg1,arg2):
def?_mydecorator1(func):
def?_mydecorator2(*args,**kw):
res=func(*args,**kw)
return?res
return?_mydecorator2
return?_mydecorator1
上面的函數(shù)返回的_mydecorator1才是真正的裝飾器。因此,當(dāng)裝飾器需要參數(shù)時(shí),必須使用第二集封裝。因?yàn)檠b飾器在模塊第一次被讀取時(shí)由解釋程序裝入,所以它們的使用必須受限于總體上可以應(yīng)用的封裝器。
帶參數(shù)及多個(gè)裝飾器:
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"
重寫(xiě)makeHtmlTag代碼:
原文:http://my.oschina.net/935572630/blog/393489
總結(jié)
以上是生活随笔為你收集整理的python重写和装饰器_python中的装饰器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mmseg java_MMSeg中文分词
- 下一篇: 达摩院2023十大科技趋势发布 生成式A