• Python 函数作用域


    外部不能访问函数内部变量

    >>> def fun1():
    	x = 1
    
    >>> print(x)
    
    #结果
    Traceback (most recent call last):
    	File "<pyshell#6>", line 1, in <module>
    		print(x)
    NameError: name 'x' is not defined
    

    函数内部能够访问函数外部变量:

    >>> x = 123
    >>> def fun2():
    			print(x)
    #结果:
    >>> fun2()  #调用函数
    123	
    

    函数里面不能修改函数外部变量:

    >>> x = 123
    >>> def  fun3():
    		x = x + 1
    		print(x)
    #结果
    Traceback (most recent call last):
    	File "<pyshell#19>", line 1, in <module>
    		fun3()
    	File "<pyshell#17>", line 2, in fun3
    		x = x+1
    UnboundLocalError: local variable 'x' referenced before assignment
    

    函数里面和函数外部变量名相同:

    >>> x = 123
    >>> print(x, id(x))
    123 8791238636176
    >>> def fun4():
    		x = 456
    		print(x, id(x))
    >>> fun4()
    #结果
    456 45350000
    

    说明

    1.变量是先定义,再使用。

    2.如果在最近的作用域里有定义,就会使用最近作用域的变量。

    3.如果在函数里面没有定义,它会往它的外层去找。

    4.如果外层有定义,就使用.

    global(全局变量)

    >>> x = 123
    >>> def fun1():
    	global x
    	x+=1
    	return x
    
    >>> fun1()
    124
    

    nonlocal(上一级函数中的局部变量)

    在函数嵌套函数的情况下,同样也有函数作用域的问题,python3中提供了方便,只需要使用nonlocal就可以在里层函数内部修改外部函数变量.

    >>> def fun2():
    	x = 123
    	def fun3():
    		nonlocal x
    		x+=1
    		return x
    	return fun3()
    
    >>> fun2()
    124
    
  • 相关阅读:
    axis2的wsdl无法使用eclipse axis1插件来生成client--解决方法
    引用的存在价值
    阿里亲心小号实測
    UVA 1328
    XMPP 协议工作流程具体解释
    10g异机恢复后EM无法启动故障处理一例
    JVM 内存
    abstract class和interface有什么区别?
    ArrayList 如何增加大小
    IndexOutOfBoundsException ArrayList 访问越界
  • 原文地址:https://www.cnblogs.com/jiajiaba/p/10639628.html
Copyright © 2020-2023  润新知