函数式编程之参数详解

1、函数的返回值。python返回值比较诡异。呵呵,我人也可以返回,其它的函数,这时会返回函数的内存地值。如return test1.

 1 def test1():
 2     print("in the test1")
 3     #print("in the test")
 4 
 5 def test2():
 6     print("in the test2")
 7     return 0
 8 
 9 def test3():
10     print("in the test3")
11 
12     return 1,'hello',['zfp','lipei'],{'name':'zfp'}
13     #python灵活的返回方式,象超市的购物袋。
14 x=test1()
15 y=test2()
16 z=test3()
17 
18 print(x)
19 print(y)
20 print(z)

2、形参与实参。

位置参数与关键字参数,位置参数必须在关键字参数的左边。

 1 def test(x,y,z):
 2     print(x)
 3     print(y)
 4     print(z)
 5 
 6 #形参和实参要了解清楚
 7 #x=1
 8 #y=2
 9 #位置参数调用,与形参顺序一一对应。关键字调用,与形参位置无关。只要调用时有逻辑错误,就会报错。关键参数是不能写在位置参数前面的。
10 #test(x=x,y=y)
11 #test(y=2,x=1)
12 test(3,z=2,y=6)

默认参数

 1 '''def test(x,y=2):
 2     print(x)
 3     print(y)
 4 
 5 test(1,4)
 6 #默认参数的特点:调用时,默认参数非必须传递
 7 #用途:1、默认安装值,2、链接数据库的端口号。
 8 '''
 9 def test (x,y)
10     print(x)
11     print(y)
12 test(1,2,3)

当实参数不固定的时候,如何设计形参?用*args,接收N个位置参数,转换成元组的形式。

 1 '''def test(x,y=2):
 2     print(x)
 3     print(y)
 4 
 5 test(1,4)
 6 #默认参数的特点:调用时,默认参数非必须传递
 7 #用途:1、默认安装值,2、链接数据库的端口号。
 8 '''
 9 '''
10 def test (*args):#args也可在这成别的字符串吗,答: 可以
11     print(args)
12 
13 test(1,2,3,4,5)
14 test(*[1,2,4,5,5])# args=[1,2,4,5,5]
15 '''
16 def test1(x,*args):
17     print(x)
18     print(args)
19 test1(1,2,3,4,5,6)

如何用到字典参数呢?用**kwargs,接受N个关键参数。

1 def test3(name,age=18,*args,**kwargs):
2     print(name)
3     print(age)
4     print(args)
5     print(kwargs)
6 
7 #test3('zfp','lisi') #这里会出错
8 test3('zfp',34,sex='M',hobby='pengpengqiu')

 

posted @ 2020-02-06 01:04  奔腾的小河  阅读(602)  评论(0编辑  收藏  举报