参考文档:https://www.runoob.com/python3/python3-namespace-scope.html
作用域作用域就是一个 Python 程序可以直接访问命名空间的正文区域。
在一个 python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则会报未定义的错误。
Python 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。
变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称
作用域类型 L(Local):最内层,包含局部变量,比如一个函数/方法内部。 E(Enclosing):包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数,一个函数(或类) A 里面又包含了一个函数 B ,那么对于 B 中的名称来说 A 中的作用域就为 nonlocal。 G(Global):当前脚本的最外层,比如当前模块的全局变量。 B(Built-in): 包含了内建的变量/关键字等。最后被搜索name=‘小红‘ #全局作用域def xiaolu(): name=‘小路‘ #闭包函数外得函数Enlcosing print(name) def xiaohuang(): name="小黄" #局部作用域
#内置作用域是通过一个名为 builtin 的标准模块来实现的,但是这个变量名自身并没有放入内置作用域内,所以必须导入这个文件才能够使用它#python3.0 查看预定了那些的变量>>>import builtins>>>dir(builtins)[‘ArithmeticError‘,‘AssertionError‘,‘AttributeError‘,‘BaseException‘,‘BlockingIOError‘,‘brokenPipeError‘,‘BufferError‘,‘BytesWarning‘,‘ChildProcessError‘,‘ConnectionAbortedError‘,‘ConnectionError‘,‘ConnectionRefusedError‘,‘ConnectionresetError‘,‘DeprecationWarning‘,‘EOFError‘,‘Ellipsis‘,‘EnvironmentError‘,‘Exception‘,‘False‘,‘fileExistsError‘,‘fileNotFoundError‘,‘floatingPointError‘,‘FutureWarning‘,‘GeneratorExit‘,‘IOError‘,‘importError‘,‘importWarning‘,‘IndentationError‘,‘IndexError‘,‘InterruptedError‘,‘IsADirectoryError‘,‘KeyError‘,‘KeyboardInterrupt‘,‘LookupError‘,‘MemoryError‘,‘ModuleNotFoundError‘,‘nameError‘,‘None‘,‘NotADirectoryError‘,‘NotImplemented‘,‘NotImplementedError‘,‘OSError‘,‘OverflowError‘,‘PendingDeprecationWarning‘,‘PermissionError‘,‘ProcessLookupError‘,‘RecursionError‘,‘ReferenceError‘,‘ResourceWarning‘,‘RuntimeError‘,‘RuntimeWarning‘,‘StopAsyncIteration‘,‘stopiteration‘,‘SyntaxError‘,‘SyntaxWarning‘,‘SystemError‘,‘SystemExit‘,‘TabError‘,‘TimeoutError‘,‘True‘,‘TypeError‘,‘UnboundLocalError‘,‘UnicodeDecodeError‘,‘UnicodeEncodeError‘,‘UnicodeError‘,‘UnicodeTranslateError‘,‘UnicodeWarning‘,‘UserWarning‘,‘ValueError‘,‘Warning‘,‘windowsError‘,‘ZerodivisionError‘,‘__build_class__‘,‘__deBUG__‘,‘__doc__‘,‘__import__‘,‘__loader__‘,‘__name__‘,‘__package__‘,‘__spec__‘,‘abs‘,‘all‘,‘any‘,‘ascii‘,‘bin‘,‘bool‘,‘breakpoint‘,‘bytearray‘,‘bytes‘,‘callable‘,‘chr‘,‘classmethod‘,‘compile‘,‘complex‘,‘copyright‘,‘credits‘,‘delattr‘,‘dict‘,‘dir‘,‘divmod‘,‘enumerate‘,‘eval‘,‘exec‘,‘execfile‘,‘exit‘,‘filter‘,‘float‘,‘format‘,‘froZenset‘,‘getattr‘,‘globals‘,‘hasattr‘,‘hash‘,‘help‘,‘hex‘,‘ID‘,‘input‘,‘int‘,‘@R_301_3376@‘,‘issubclass‘,‘iter‘,‘len‘,‘license‘,‘List‘,‘locals‘,‘map‘,‘max‘,‘memoryview‘,‘min‘,‘next‘,‘object‘,‘oct‘,‘open‘,‘ord‘,‘pow‘,‘print‘,‘property‘,‘quit‘,‘range‘,‘repr‘,‘reversed‘,‘round‘,‘runfile‘,‘set‘,‘setattr‘,‘slice‘,‘sorted‘,‘staticmethod‘,‘str‘,‘sum‘,‘super‘,‘tuple‘,‘type‘,‘vars‘,‘zip‘]内置作用域名
规划顺序: L –> E –> G –>B。
在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内置中找。
注意
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问
>>>if 1: msg=‘1223‘ >>>msg‘1223‘
#测试1-调用函数def test(): print("test的函数")print(test) #输出的 <function test at 0x00FD9738>test() #调用函数test()#测试2-调用函数test返回函数test1的内存地址,输出test1的内存地址def test1(): print("test1的函数")def test(): print("test的函数") return test1res = test() #返回test1的内存地址赋值给resprint(res) #输出"""执行结果test的函数<function test1 at 0x00FD96F0>"""#测试3-调用函数test返回函数test1的内存地址,再次调用test1()def test1(): print("test1的函数")def test(): print("test的函数") return test1res = test()print(res())"""运行结果test的函数test1的函数None"""通过函数名称调用
#测试1name=‘susu‘def test(): name=‘sugh‘ print(name) def bar(): name=‘susu‘ print(name) return barres = test()res()"""执行结果sughsusu"""#测试2name=‘susu‘def test(): name=‘sugh‘ print(name) def bar(): #name=‘susu‘ print(name) return barres = test()res()"""执行结果sughsugh"""#测试3name=‘susu‘def test(): name=‘sugh‘ print(‘----‘,name) def bar(): name=‘susu‘ print(‘------‘,name) return bartest()()"""执行结果---- sugh------ susu"""总结
以上是内存溢出为你收集整理的Python3基础-函数作用域全部内容,希望文章能够帮你解决Python3基础-函数作用域所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)