Python:函数+对象+模块
一.
>>> def FirstFounction(): print("创建的第一个函数") >>> FirstFounction() 创建的第一个函数
二.形参和实参:
>>> def SecondFounction(name): print(name + "I love you") >>> SecondFounction('summer') summerI love you
三。关键字参数(给参数加一个定义)
>>>SecondFounction(name = 'summer')
四.默认参数
五.收集参数(作者都搞不清到底要几个参数)
>>> def SecondFounction(*name):
六.函数与过程
1.
>>> def hello(): print("创建summer") >>> temp = hello() 创建summer >>> temp >>> print(temp) None >>> type(temp) <class 'NoneType'> >>> def back(): return['summer',1,4] >>> back() ['summer', 1, 4]
2.栈函数职能访问一遍 ;
3.全局变量使用要小心(函数内部试图重新定义全局变量,其实在函数内部变为初步变量,外部还是全局变量,两个不会相互影响),所以函数内部可以访问全局变量,但不可以修改全局变量;
>>> a = 10 >>> def function(): a = 26 print("打印a:",a) >>> function() 打印a: 26 >>> a 10
函数内部global 定义全局变量;
七.函数与闭包
1.内嵌函数
2.闭包:函数式编程的一种重要方式
>>> def funx(x): def funy(y): return x * y return funy >>> a = funx(8) >>> a.funy at 0x00000000003D2E18> >>> type(a) <class 'function'> >>> funx(8)(5) 40 >>> funy(5) Traceback (most recent call last): File " ", line 1, in funy(5) NameError: name 'funy' is not defined
>>> def fun1(): x = 5 def fun2(): x *= x return x return fun2() >>> fun1() Traceback (most recent call last): File "", line 1, in fun1() File " ", line 6, in fun1 return fun2() File " ", line 4, in fun2 x *= x UnboundLocalError: local variable 'x' referenced before assignment //x被封闭 无法调用 >>> def fun1(): x = [5] def fun2(): x[0] *= x[0] return x[0] return fun2() >>> fun1() 25 >>> def fun1(): x = 5 def fun2(): nonlocal x x *= x return x return fun2() >>> fun1() 25
八.匿名函数
1.
>>> def fun(x): return 2 * x + 1 >>> fun(4) 9 >>> lambda x : 2 * x + 1lambda> at 0x0000000001D12E18>
lambda表达式重要作用:
(1)省下函数定义过程;
(2)命名;
(3)简化可读性;
2.两个牛逼的BIF
(1)filter() //Python的过滤器
>>> filter(None,[2,3,False,True])>>> list(filter(None,[2,3,False,True])) [2, 3, True]
>>> def odd(x): return x % 2 >>> temp = range(15) >>> show = filter(odd,temp) >>> list(show) [1, 3, 5, 7, 9, 11,13]
转化为一行实现:
>>> list(filter(lambda x : x % 2 , range(15))) [1, 3, 5, 7, 9, 11, 13]
(2)map();
>>> list(map(lambda x : x * 2 , range(15))) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]