1.請(qǐng)實(shí)現(xiàn)一個(gè)裝飾器,把函數(shù)的返回值+100然后返回
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
def wapper(func): def innner( * args, * * kwargs): ret = func( * args, * * kwargs) ret = print (ret + 100 ) return ret return innner @wapper def func(number): return int (number) func( 100 ) ###結(jié)果:200 |
2.請(qǐng)實(shí)現(xiàn)一個(gè)裝飾器,通過一次調(diào)用使函數(shù)重復(fù)執(zhí)行5次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#Python學(xué)習(xí)交流群:725638078 def wapper(func): def innner( * args, * * kwargs): count = 0 while count< 5 : func( * args, * * kwargs) count + = 1 return innner @wapper def func(): print ( "執(zhí)行" ) func() |
3.請(qǐng)實(shí)現(xiàn)一個(gè)裝飾器每次調(diào)用函數(shù)時(shí),將函數(shù)名字及調(diào)用函數(shù)的時(shí)間點(diǎn)寫入文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import time def wapper(func): def inner( * args, * * kwargs): with open ( "log" ,encoding = "utf-8" ,mode = "a+" ) as f: structime = time.localtime() f.write(f '北京時(shí)間:{time.strftime("%Y-%m-%d %H:%M:%S",structime)} 函數(shù)名字為:{func.__name__}\n' ) ret = func( * args, * * kwargs) return ret return inner @wapper def func(): print ( "執(zhí)行" ) func() |
到此這篇關(guān)于 Python裝飾器的練習(xí)題的文章就介紹到這了,更多相關(guān)裝飾器 習(xí)題內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
結(jié)尾給大家推薦一個(gè)非常好的學(xué)習(xí)教程,希望對(duì)你學(xué)習(xí)Python有幫助!
原文鏈接:https://www.cnblogs.com/xxpythonxx/p/15574404.html