28、python基础学习-函数作用域

 1 #!/usr/bin/env python
 2 #__author: hlc
 3 #date: 2019/6/1
 4 
 5 # if True :
 6 #     x = 3
 7 # print(x) # 3
 8 
 9 # def f() :
10 #     x = 3
11 # print(x) # NameError: name 'x' is not defined
12 """
13 作用域介绍:python中的作用域分四种情况
14 L:local,局部作用域,即函数中定义的变量;
15 E:enclosing,嵌套的父级函数局部作用域,既包含此函数的上级函数的局部作用域,但不是全局的;
16 G:globa,全局变量,就是模块级别定义的变量;
17 B:built-in,系统固定模块里面的变量,比如,int,bytearray等。
18 搜索变量的优先级顺序依次是:局部作用域》外部作用域》当前模块中的全局》python内置作用域,作用域的优先级是“LEGB”
19 """
20 # x = int(2.9) # built-in
21 #
22 # g_count = 0 # globa
23 #
24 # def outer() :
25 #     o_count = 1 # enclosing
26 #     def inner() :
27 #         i_count = 2 # local
28 #         print(o_count)
29 #     print(i_count) # 找不到
30 #     inner()
31 # outer()
32 #
33 # print(o_count) # 找不到
34 
35 # count = 10
36 # def outer() :
37 #     global count
38 #     print(count)
39 #     count = 5
40 #     print(count)
41 # outer()
42 
43 # count = 0
44 # def outer() :
45 #     count = 10
46 #     def inter() :
47 #         nonlocal count
48 #         print(count)
49 #         count = 5
50 #         print(count)
51 #     inter()
52 #     print(count)
53 # outer()
54 
55 """
56 作用域小结:
57 1、变量的查找的顺序是:LEGB,作用域局部》外部作用域》当前模块中的全局》python内置作用域;
58 2、只有模块、类、函数才能引入新作用域;
59 3、对于一个变量,内部作用域先声明就会覆盖外部环境变量,不声明直接使用,就会使用外部作用域的变量;
60 4、内部作用域要修改外部作用域变量时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal关键字。nonlocal是python3新增的关键字,有了这个关键字就能完美实现闭包了。
61 """
"""
作用域的产生:
在python中,只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其他的代码块(如:if、try、for)是不会引入新的作用域的
"""
# 例如:
# if 2 > 1 :
#     x = 3
# print(x) # 3
# 这个是没有问题的,if并没有引入新的作用域,x仍处在当前作用域中,后面代码可以使用

# def test() :
#     x = 3
# print(x) # NameError: name 'x' is not defined

# def class lambda是可以引入新作用域的
# count = 10
# def outer() :
#     print(count) # UnboundLocalError: local variable 'count' referenced before assignment
#     count = 5
#     print(count)
# outer()
"""
1、报错的原因在于print(count)时,解释器会在本地作用域查找,会找到count = 5(此时函数已经被加载到内存)
2、UnboundLocalError: local variable 'count' referenced before assignment 证明已经count = 5 ,使用global声明变量为全局,可以解决此问题
3、如果都没有找到会报 NameError: name 'count' is not defined
"""

  

  


 

posted @ 2019-06-01 23:11  hlc-123  阅读(152)  评论(0编辑  收藏  举报