第33天pytho学习装饰器:高级函数部分演示

时间:2019-09-28
本文章向大家介绍第33天pytho学习装饰器:高级函数部分演示,主要包括第33天pytho学习装饰器:高级函数部分演示使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#迭代器:把列表变为迭代器
# l=[1,3]
# l1=iter(l)#转换成迭代器
# print(l1)
# print(next(l1))#——————转换成迭代器把第一个值取出来

#装饰器:本质就是函数;功能:为其他函数添加附加功能
#原则:1、不修改被修饰函数的源代码 2、不修改被修饰函数的调用方式

#统计函数的时间
# import time#添加个时间模块
# def test(l):
# start_time=time.time()#开始时间
# res=0
# for i in l:
# time.sleep(0.1)#让函数睡0.1秒
# res+=i
# stop_time=time.time()#停止时间
# print("运行时间函数时间 %s" %(stop_time-start_time))
# return res
# print(test(range(100)))

#装饰器的好处:就是解决已经在运行的函数添加功能,不可能把之前的函数拿出从新搞,避免其他地方在应用


#演示的装饰器-------------------运行有问题等修改
import time#添加个时间模块
#使用装饰器来修饰下面求值的函数
# def time(fun):
# def wapper(*args,**kwargs):
# start_time=time.time()
# res=fun(*args,**kwargs)
# stop_time=time.time()
# print("函数运行时间 %s" %(stop_time-start_time))
# return res
# return wapper
#
# #函数求职
# @time
# def test(l):
# res=0
# for i in l:
# time.sleep(0.1)#让函数睡0.1秒
# res+=i
# return res
# print(test(range(20)))

#装饰器知识储备:装饰器=高级函数+函数嵌套+闭包

#高级函数:1、函数接收的参数是一个函数名;2、函数的返回值是一个函数。只要满足1或2任意一个条件都可以称之为高级函数

# def foo():
# print("您好foo")
#
# #这个是高级函数
# def test(fun):
# print(fun)
# fun()#执行运行结果
# test(foo)

# #求foo的运行时间,但是以下方法实现了没有修改原函数就实现求值,但是修改了调用函数的方式
# import time
# def foo():
# time.sleep(0.1)
# print("您好foo")
#
# #这个是高级函数,参数是函数名的方式
# def test(fun):
# print(fun)
# start_time=time.time()
# fun()#执行运行结果
# stop_time=time.time()
# print("foo运行时间 %s" %(stop_time-start_time))
# test(foo)#正确的方式是直接foo()执行,但是我这使用了test(foo),修改了函数的调用方式



#使用高级函数:返回值和参数都是函数
# def foo():
# print("函数 foo")
#
# def test(fun):
# return fun
#
# res=test(foo)#拿到地址
# res()#直接运行


# #实现不改调用函数方式
# def foo():
# print("函数 foo")
#
# def test(fun):
# return fun
# foo=test(foo)#在赋值给foo
# foo()#调用方式还是foo()


#统计foo运行时间,不修改foo原代码,不修改foo的调用方式

#多运行一次了,失败的列子
# import time
# def foo():
# time.sleep(3)
# print("来自 foo")
#
# def time1(fun):
# start_time=time.time()
# fun()#执行运行结果
# stop_time=time.time()
# print("foo运行时间 %s" %(stop_time-start_time))
# return fun
#
# foo=time1(foo)
# foo()#结果:来自 foo foo运行时间 3.000626564025879 来自 foo

#总结:上面应用了高级函数,但是实现不了装饰器



#总结:1、使用传入参数是函数时,没有修改原来函数,但是修改了调用方式。
# 2、使用返回值是函数时,不修改调用方式

原文地址:https://www.cnblogs.com/jianchixuexu/p/11605370.html