python裝飾器 函式裝飾器,類裝飾器

2021-08-20 12:41:20 字數 3417 閱讀 1223

只要實現此

模式,這個obj就叫乙個裝飾器

------------------------------>參考

函式裝飾器

例子--

-def

decorator

(func)

:def

inner

(*args,

**kwargs)

:print

('before...........'

) res = func(

*args,

**kwargs)

print

('after............'

)return res

return inner

@decorator

defrun()

:print

('run...............'

)return

0if __name__ ==

"__main__"

: run(

) run.__name__

# 此時decorator叫做裝飾器--

----

----

----

----

----

----

----

----

----

----

before...

....

....

run...

....

....

....

after...

....

....

.inner

注意:inner的返回值要與func的一致,並且inner與func引數相同

from functools import wraps

defdecorator

(func)

: @wraps(func)

definner()

:print

('before...........'

) res = func(

)print

('after............'

)return res

return inner

@decorator

defrun()

:print

('run...............'

)return

0if __name__ ==

"__main__"

: run(

)print

(run.__name__)--

----

----

----

----

----

----

----

----

----

----

before...

....

....

run...

....

....

....

after...

....

....

.run

from functools import wraps

from datetime import datetime

defstart()

:return datetime.now(

)def

end():

return datetime.now(

)def

filter

(start_time, end_time)

:def

decorator

(func)

: @wraps(func)

definner

(*args,

**kwargs)

: s = start_time(

) res = func(

*args,

**kwargs)

e = end_time(

)print

("耗時{}"

.format

((e-s)

.total_seconds())

)return res

return inner

return decorator

@filter(start, end)

defrun()

:for i in

range

(10000):

for j in

range

(100):

print

(j)return

0if __name__ ==

"__main__"

: run(

)

變種(擷取自flask @route())

類裝飾器

class

decorator

(object):

def__init__

(self, func)

: self.func = func

def__call__

(self,

*args,

**kwargs)

:print

('before............'

) res = self.func(

*args,

**kwargs)

print

('after............'

)return res

@decorator

defrun()

:print

('run............'

)if __name__ ==

"__main__"

: run()-

----

----

----

----

----

----

----

----

--before...

....

....

.run...

....

....

.after...

....

....

.

python 裝飾器 函式裝飾器 類裝飾器

python函式裝飾器和類裝飾器筆記.usr bin env python coding utf 8 author ivan file decorators.py version from functools import wraps 裝飾器 目的是為了給函式新增附加功能 1.不帶引數裝飾器 此方式...

函式裝飾器 類裝飾器

一 函式裝飾函式 defwrapfun func definner a,b print function name func.name r func a,b return r return inner wrapfun defmyadd a,b return a b print myadd 2,3 二...

python裝飾器 裝飾器工廠函式

使用裝飾器實現如下所示的列印 小白聯盟def printequel func1 def inner1 print 15 func1 return inner1 def printstar func2 def inner2 print 15 func2 return inner2 printequel...