python 函数与函数式编程

1,三种编程的规范 a,面向对象

                                b,面向过程

                                c,函数式编程

def 关键词:过程可以理解为没有返回值的函数,但是在python中过程和函数没有严格的界限

 1 #定义函数
 2 def func1():
 3     '''testing1'''
 4     print('in the func1')
 5     return 0
 6 
 7 #定义过程
 8 def func2():
 9     '''testing2'''
10     print ('in the func2')
11 
12 x=func1()
13 y=func2()
14 
15 print ('from func1 return is %s'%x)
16 print ('from func2 return is %s'%y)
17 
18 输出:
19 in the func1
20 in the func2
21 from func1 return is 0
22 from func2 return is None

 2,函数的好处

  a,可扩展

  b,保持一致

  c,代码重用

 1 #日志模拟代码
 2 def logger():
 3     with open('a.txt','a+') as f1:
 4         f1.write('end action\n')
 5 
 6 def test1():
 7     print('test1\n')
 8     logger()
 9 def test2():
10     print('test2\n')
11     logger()
12 def test3():
13     print('test3\n')
14     logger()
15 test1()
16 test2()
17 test3()
18 输出:
19 test1
20 
21 test2
22 
23 test3
24 输出文件:a.txt
25 end action
26 end action
27 end action
28 
29 #修改logger函数,增加时间打印
30 import time
31 
32 def logger():
33     time_format='%Y-%M-%D %X'#定义时间格式,%X表示时分秒
34     time_current=time.strftime(time_format)#套用上面的时间格式打印时间
35     with open('a.txt','a+') as f:
36         f.write('%s time_end action\n'%time_current)
37 #以下调用不变
38 def test1():
39     print('test1\n')
40     logger()
41 def test2():
42     print('test2\n')
43     logger()
44 def test3():
45     print('test3\n')
46     logger()
47 test1()
48 test2()
49 test3()
50 输出:
51 test1
52 
53 test2
54 
55 test3
56 输出文件:a.txt
57 end action
58 end action
59 end action
60 2017-09-11/30/17 11:09:16 time_end action
61 2017-09-11/30/17 11:09:16 time_end action
62 2017-09-11/30/17 11:09:16 time_end action

#注意:以上仅仅修改了logger函数,调用等内容均没有变化

3,函数返回值

  return语句之后的代码不会被执行

 1 def test4():
 2     print('in the test4')
 3     return 0
 4     print('in the test4')
 5 test4()
 6 
 7 输出:
 8 in the test4#注意,第二次print在return之后,将不会被打印
 9 
10 def test1():
11     print ('in the test1')
12 
13 def test2():
14     print ('in the test2')
15     return 0
16 
17 def test3():
18     print ('in the test3')
19     return 1,'hello',['69式','老汉推车'],{'服务内容':'冰火2重天'}
20 x=test1()
21 y=test2()
22 z=test3()
23 print(x)
24 print(y)
25 print(z)
26 
27 输出:
28 in the test1
29 in the test2
30 in the test3
31 None
32 0
33 (1, 'hello', ['69式', '老汉推车'], {'服务内容': '冰火2重天'})
34 #返回的数据没有类型的限制,也没有数量的限制(会以元组方式返回)

4,

  

posted on 2017-11-29 14:21  敏少爷  阅读(175)  评论(0编辑  收藏  举报

导航