zoukankan      html  css  js  c++  java
  • 关于Python中的装饰器理解

    装饰器的作用就是代码重用!!!!
    import time
    
    # 定义一个能够直接测试程序运行时间的代码
    def timeNumber(func):
    	frontTime = time.time()
    	func()
    	endTime = time.time()
    	print("这个程序花了%f毫秒" % ((endTime - frontTime) * 1000))
    
    def myfunc():
    	print("function Go........")
    	time.sleep(2)
    	
    print("调用函数执行》》》》》》")
    timeNumber(myfunc)
    print("调用函数执行结束 《《《《《《")


    在每次都直接调用函数,并且在结束后,myfunc并没用变为一个带有timeNumber函数功能的新函数,如果要再用timeNumber功能又得重新调用timeNumber(myfunc)比较麻烦

    这时候就可以使用装饰器来实现一劳永逸的效果,看下面:

    def timeNumber(func):
    	def wrapper():
    		frontTime = time.time()
    		func()
    		endTime = time.time()
    		print("这个程序花了%f毫秒" % ((endTime - frontTime) * 1000))
    	return wrapper
    
    def myfunc():
    	print("function Go........")
    	time.sleep(2)
    	
    print("装饰器调用执行》》》》》》")
    myfunc = timeNumber(myfunc)
    myfunc()
    print("装饰器调用执行结束 《《《《《《")
    print("重新调用myfunc()")
    myfunc()
    执行结果,只要装饰一次,则调用myfunc()则后续都有timeNumber()函数的功能

    为了简便使用装饰器语法糖@,效果等同于 这一句 myfunc = timeNumber(myfunc)

    @timeNumber
    def myfunc():
    	print("function Go........")
    	time.sleep(2)
    调用结果与上面一致


    如果在用语法糖装饰后,调用myfunc的__name__则显示的是wrapper的名字,表明已经被装饰


  • 相关阅读:
    CodeForces 659F Polycarp and Hay
    CodeForces 713C Sonya and Problem Wihtout a Legend
    CodeForces 712D Memory and Scores
    CodeForces 689E Mike and Geometry Problem
    CodeForces 675D Tree Construction
    CodeForces 671A Recycling Bottles
    CodeForces 667C Reberland Linguistics
    CodeForces 672D Robin Hood
    CodeForces 675E Trains and Statistic
    CodeForces 676D Theseus and labyrinth
  • 原文地址:https://www.cnblogs.com/jlxa162hhf/p/14161270.html
Copyright © 2011-2022 走看看