Python初学教程:变量的作用域,python初学变量,如下代码演示变量作用域。


如下代码演示变量作用域。

#!/usr/bin/python# 定义一个全局变量snogglesnoggle = 17#在wongle方法中使用了snoggle,这是snoggle是函数体内的局部变量,其引用的并非上面定义的全局变量def wongle(n):    snoggle = nprint 'A:', snoggle,wongle(235)print snoggle# 下面函数wangle函数体内也使用了snoggle,但是在使用之前使用global snoggle引入了全局变量def wangle(n):    global snoggle    snoggle = nprint 'B:', snoggle,wangle(235)print snoggle# 函数值类型参数是按值传递的def snapple(n):    n = 55print 'C:', snoggle,wangle(snoggle)print snoggle# 而对于像list这样的引用类型参数,则是传引用的def snarffle(z):    z.append(22)toggle = [ 'a', 'b', 'c' ];print 'D:', toggle,snarffle(toggle)print toggle# ...which means the contents of the object, not the parameter.def snarggle(z):    z = [ 4, 5 ]print 'F:', toggle,snarggle(toggle)print toggle

在python中函数参数的传递方式和java中很想。 参数是传值的,因此在函数体内修改参数的值,并不会改变外部参数的值。

然后,对于引用类型来说其传递的则是指针的值,对指针属性的修改会影响到指针指向的对象。

评论关闭