zoukankan      html  css  js  c++  java
  • 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学习者

  • 相关阅读:
    POJ--2356 Find a multiple
    Trailing Zeroes (III)
    第一章 快速入门
    第二章 变量和基本类型
    第三章 标准库类型
    第四章 数组和指针
    第五章 表达式
    第六章 语句
    第七章 函数
    第八章 标准IO库
  • 原文地址:https://www.cnblogs.com/xxpythonxx/p/15574404.html
Copyright © 2011-2022 走看看