Python 2.7.10 (default, Oct 14 2015, 16:09:02) [GCC 5.2.1 20151010] on linux2Type "copyright", "credits" or "license()" for more information.>>> def fun1(): return [1,2,3]>>> print(fun1)>>> a=fun1()>>> a[1, 2, 3]>>> def fun2(): return 4,5,6>>> b=fun2()>>> b(4, 5, 6)>>> def fun3(): print "hello woeld" >>> c=fun3()hello woeld>>> c>>> c>>> print(fun(3))Traceback (most recent call last): File " ", line 1, in print(fun(3))NameError: name 'fun' is not defined>>> type(c) >>> print(c)None>>> type(c) >>>
函数的返回值可以是一个列表或一个元组,如果没有return,那么仍然会返回一个NONE,类型那个为typenone,
对于全局ii变量,我们在函数中只能进行引用,而不能进行修改
局部在堆栈中分配,
当我们你试图在函数中修改全局变量的时候,python会发生屏蔽,会在函数中发生屏蔽机制,额外创建一个临时变量,只能对临时变量进行修改
但是我们可通过global关键子在函数中强制对全局变量进行修改
1 >>> 2 >>> number=5 3 >>> def fun6(): 4 global number 5 number=10 6 return number 7 8 >>> fun6() 9 1010 >>> print(num)11 1012 >>> print(number)13 1014 >>>
python函数还可以进行嵌套
>>> >>> def f1(): print("fun1..") def fun2(): print("fun2")函数作用范围同c/c++ fun2() >>> f1()fun1..fun2>>>
函数都嵌套传参数,对于第一种方法,如果我们只是传了一个参数,那么会返回一个函数,表示需要想第二个函数传参数,
简单的做法就是直接连续写两个括号传两个参数
1 >>> def fun1(x): 2 def fun2(y): 3 return x*y 4 return fun2 5 6 >>> fun1() 7 8 Traceback (most recent call last): 9 File "", line 1, in 10 fun1()11 TypeError: fun1() takes exactly 1 argument (0 given)12 >>> fun1(5)13 14 >>> type(fun1(5))15 16 >>> i=fun1(5)17 >>> i(10)18 5019 >>> fun1(3)(8)20 24
对于python3.0之前,为了可以在局部对外部变量进行改变,因为list不是在堆栈山申请的,所以我们可以改变外部的list变量
1 >>> def fun5():2 x=[5]3 def fun6():4 x[0]*=x[0]5 return x[0]6 return fun6()7 8 >>> fun5()9 25
3.0之后可以只有 nonlocal
闭包就是内部函数可以使用外部的作用区间(不是全局的)进行引用,那么这个内部函数就被叫闭包