Python關於裝飾器的練習題


1.請實現一個裝飾器,把函數的返回值+100然后返回

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)
###結果:200

2.請實現一個裝飾器,通過一次調用使函數重復執行5次

#Python學習交流群:725638078

def wapper(func):
    def innner(*args,**kwargs):
        count=0
        while count<5:
            func(*args,**kwargs)
            count+=1
    return innner
@wapper
def func():
    print("執行")
func()

3.請實現一個裝飾器,每次調用函數時,將函數名字以及調用此函數的時間點寫入文件中

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'北京時間:{time.strftime("%Y-%m-%d %H:%M:%S",structime)} 函數名字為:{func.__name__}\n')
        ret=func(*args,**kwargs)
        return ret
    return inner
@wapper
def func():
    print("執行")
func()

結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!

Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者

Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM