函数的嵌套和作用域链以及闭包

注意:函数最多嵌套三层

函数的嵌套-----内部函数可以使用外部的函数

1 def max(a,b):
2     return a if a>b else b # 三元运算 :  成立返回的值 if 判断条件 else 不成立返回的值
3 
4 def the_max(x,z,y): #函数的嵌套调用
5     c = max(x,y)
6     return max(c,z)

函数的嵌套定义---内部函数可以使用外部函数的变量

 1 def test():
 2     a = 1
 3     def other():
 4         b =2
 5         print(a)
 6         print('other')
 7         def other1():
 8             print(a,b)
 9             print('other1')
10         other1()
11     other()
12 
13 print(test())

nolocal: 只能用于局部变量。找上层中离当前函数最近一层的局部变量
  声明了nolocal,的内部函数的变量修改会影响到离当前函数最近一层的局部变量
  对全局无效,对最近一层的局部变量有效
  对比global,只能修改全局变量的值

 1 a = 1
 2 def test():
 3     a = 1
 4     print(a)
 5     def test1():
 6         b = 2
 7         print(b)
 8         def test2():
 9             nonlocal a  # 局部声明变量a,若使用global 则会修改全局变量里的a
10             a += 1  #不可变数据类型的修改
11             print(a)
12             def test3():
13                 global a  # 全局声明变量a,不会修改函数内的变量a
14                 a = 100
15                 print(a)
16             test3()
17         test2()
18     test1()
19 
20 print(test())
21 print(a)

 作用域链

1 def f1():
2     a = 1
3     def f2():
4         a = 2
5     f2()
6     print('a in f1 : ',a)
7 
8 f1()

 闭包

闭包:嵌套函数,内部函数调用外部函数的变量

1 def func():
2     name = 'eva'
3     def inner():
4         print(name)

闭包得常用场景

1 #常用方法,延长了函数内值得存在周期
2 def test():
3     a = 1
4     def test_a():
5         print(a)
6     return test_a  # 直接返回一个内存地址
7 
8 aa = test() # 这是返回一个test_ad的内存地址
9 aa() # 相当于调用函数test_a()

 闭包使用案例

 1 import urllib # 导入模块 urllib
 2 from urllib.request import urlopen # 引入模块内得urlopen
 3 # ret = urlopen('https://y.qq.com/').read()
 4 # print(ret)
 5 def get_url(a):
 6     url = a
 7     def get():
 8         ret = urlopen(url).read()
 9         print(ret)
10     return get
11 
12 get_func = get_url('https://baidu.com')
13 get_func()

 

posted on 2019-02-11 16:30  Jerry-Wang  阅读(112)  评论(0)    收藏  举报