Python学习之路9——函数剖析

  1、函数的调用顺序

   错误的调用方式

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 # 函数错误的调用方式
 6 def func():  # 定义函数func()
 7     print("in the func")
 8     foo()  # 调用函数foo()
 9 
10 func()  # 执行函数func()
11 
12 def foo():  # 定义函数foo()
13     print("in the foo")

    执行结果:

 1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/func.py
 2 in the func
 3 Traceback (most recent call last):
 4   File "E:/Python/PythonLearing/func.py", line 11, in <module>
 5     func()  # 执行函数func()
 6   File "E:/Python/PythonLearing/func.py", line 8, in func
 7     foo()  # 调用函数foo()
 8 NameError: name 'foo' is not defined
 9 
10 Process finished with exit code 1

    正确的调用方式

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 #函数正确的调用方式
 6 def func():                     #定义函数func()
 7     print("in the func")
 8     foo()                       #调用函数foo()
 9 def foo():                      #定义函数foo()
10     print("in the foo")
11 func()                          #执行函数func()

   执行结果:

1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/func.py
2 in the func
3 in the foo
4 
5 Process finished with exit code 0

      总结:被调用函数要在执行之前被定义。

   2、高阶函数 

满足下列条件之一就可成函数为高阶函数

 

    • 某一函数当做参数传入另一个函数中

    • 函数的返回值包含一个或多个函数

 

刚才调用顺序中的函数稍作修改就是一个高阶函数

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 # 高阶函数
 6 def func():  # 定义函数func()
 7     print("in the func")
 8     return foo()  # 调用函数foo()
 9 
10 def foo():  # 定义函数foo()
11     print("in the foo")
12     return 100
13 
14 res = func()  # 执行函数func()
15 print(res)  # 打印函数返回值

  输出结果:

1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/func.py
2 in the func
3 in the foo
4 100
5 
6 Process finished with exit code 0

  从上面的程序得知函数func的返回值为函数foo的返回值,如果foo不定义返回值的话,func的返回值默认为None;

  下面来看看更复杂的高阶函数:

 1 #!/user/bin/env ptyhon
 2 # -*- coding:utf-8 -*-
 3 # Author: VisonWong
 4 
 5 # 更复杂的高阶函数
 6 import time  # 调用模块time
 7 
 8 def bar():
 9     time.sleep(1)
10     print("in the bar")
11 
12 def foo(func):
13     start_time = time.time()
14     func()
15     end_time = time.time()
16     print("func runing time is %s" % (end_time - start_time))
17 
18 foo(bar)

  执行结果:  

1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/func.py
2 in the bar
3 func runing time is 1.0400593280792236
4 
5 Process finished with exit code 0

  其实上面这段代码已经实现了装饰器一些功能,即在不修改bar()代码的情况下,给bar()添加了功能;但是改变了bar()调用方式

  下面我们对上面的code进行下修改,不改变bar()调用方式的情况下进行功能添加

猜你喜欢

转载自www.cnblogs.com/visonwong/p/8995714.html