#变量作用域,在自己屋子干自己的事儿
#LEGB
#本地、封闭、全局、内置
#局部变量
x = 1 #全局变量 def add(): x += 1 #局部变量 print(x) add()
#结果会报错,这是为什么呢?因为局部变量没有被赋值
#全局变量
x = 99 def add() print(x) add()
#没有局部变量,可以使用全局变量代替
#案例
error_list = [2,3,5] def big_list(): error_list.append(88) print(error_list) big_list()
error_list = [2,3,5]
def big_list():
new_list = error_list
new_list += [99]
print(new_list)
big_list()
#函数嵌套
函数是python里面的一级对象,可以用在任何地方,比如函数里面,这时候的作用域属于封闭作用域
一级对象:
1.在运行时创建
2.能赋值给变量或数据结构
扫描二维码关注公众号,回复:
5618750 查看本文章
3.能作为参数传递给函数
4.能作为函数的返回结果
def calc(x,y): def add(x,y): print(x+y) def sub(x,y): print(x-y) def mul(x,y): print(x*y) return add,sub,mul c = calc(3,5)
print(c)
#闭包
def hello() s = "zaishui" def say() s += "who this is" print(s) return say hello()