Python3 day4

 今日内容:

1、高阶函数

   2、嵌套函数

   3、装饰器

1、高阶函数

         定义:

                a:把一个函数名当作实参传给函数

                    a:返回值包含函数名(不修改函数的调用方式)

import time
def test1():
    time.sleep(3)
    print('in the test1')


def func(fun):
    start_time=time.time()
    fun()
    stop_time=time.time()
    print("fun use time:%s" %(stop_time-start_time))

func(test1)
View Code

2、嵌套函数

def foo():
    print('in the foo')
    def bar():
        print('in the bar')

    bar()
foo()
View Code

函数调用

 1 import time
 2 def test1():
 3     time.sleep(3)
 4     print('in the test1')
 5 
 6 
 7 def func():
 8     test1()
 9     
10    
11 func()
View Code

3、装饰器

定义:本质是函数,(装饰其他函数)就是为其它函数添加附加功能。

原则:1、不能修改被装饰器函数的源代码

              2、不能修改被装饰函数的调用方式

函数即“变量”

高阶函数 + 嵌套函数  ----》装饰器

 1 import time
 2 def timer(func):
 3     def deco(*args,**kwargs):
 4         start_time=time.time()
 5         func(*args,**kwargs)# run  test1()
 6         stop_time=time.time()
 7         print("the func run time is:%s"%(stop_time-start_time))
 8     return deco
 9 @timer#test1=timer(test1)  test1=deco  test1()==deco()
10 def test1():
11     print("in the test1")
12     time.sleep(3)
13 @timer
14 def test2(name,age):
15     print("in the test2",name,age)
16 
17 
18 test1()
19 test2('鲁班',12)
View Code

猜你喜欢

转载自www.cnblogs.com/yunwangjun-python-520/p/9833747.html
今日推荐