加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python3基础-函数作用域

发布时间:2020-12-20 10:17:33 所属栏目:Python 来源:网络整理
导读:参考文档:https://www.runoob.com/python3/python3-namespace-scope.html 作用域 作用域就是一个 Python 程序可以直接访问命名空间的正文区域。 在一个 python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则会报未定义的错误。

参考文档: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,isinstance,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 test1

res = test() #返回test1的内存地址赋值给res
print(res) #输出
"""
执行结果
test的函数
<function test1 at 0x00FD96F0>
"""

#测试3-调用函数test返回函数test1的内存地址,再次调用test1()
def test1():
    print("test1的函数")

def test():
    print("test的函数")
    return test1

res = test()
print(res())

"""
运行结果
test的函数
test1的函数
None
"""
通过函数名称调用
#测试1
name=susu
def test():
    name=sugh
    print(name)
    def bar():
        name=susu
        print(name)
    return bar

res = test()
res()
"""
执行结果
sugh
susu
"""

#测试2
name=susu
def test():
    name=sugh
    print(name)
    def bar():
        #name=‘susu‘
        print(name)
    return bar

res = test()
res()
"""
执行结果
sugh
sugh
"""
#测试3
name=susu
def test():
    name=sugh
    print(----,name)
    def bar():
        name=susu
        print(------,name)
    return bar

test()()
"""
执行结果
---- sugh
------ susu
"""

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读