赞
踩
def outer():
inner() # error
def inner():
print("我是内函数 ... ")
inner() # success
inner()
outer()
inner()
outer()
outer()
python 语法 必须要先定义函数 , 在调用函数
在其他语言中,可以先调用在定义,是允许的;
因为在其他语言当中, 存在预加载机制:
在编译代码之前,先把文件中的所有的函数,提前加载到内存中
然后才真正的编译全部的文件代码
python目前版本,还没有预加载的机制,所以只能先定义在调用;
outer函数的定义处 a = 400 id = 500 def outer(): a = 300 def inner(): # inner的定义处 a = 200 def smaller(): # smaller的定义处 a = 100 print("我是smaller函数", a) print(id) smaller() # smaller的调用处 inner() # 调用inner 函数 outer() # 函数的调用处
找寻变量的调用顺序采用LEGB原则(即就近原则)
B —— Builtin(Python); Python内置模块的命名空间 (内建作用域)
G —— Global(module); 函数外部所在的命名空间 (全局作用域)
E —— Enclosing function locals;外部嵌套函数的作用域 (嵌套作用域)
L —— Local(function);当前函数内的作用域 (局部作用域)
依据就近原则,从下往上 从里向外 依次寻找
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。