函数与函数式编程
编程的3种方法:
面向过程: 过程 def
面向对象 : 类 class
函数式编程: 函数 def
函数式编程,比较古老的一种编程方式:函数式编程,以其不保存状态,不修改变量等特性重回人们视线。
1. 函数
函数的定义:
def test1(): print('internet') return 0 x = test1() print(x)
2. 为何使用函数?
没有函数的编程就是在写逻辑(功能),但没有函数,想重复使用你的逻辑,唯一的方法就是copy。
with open('a.txt','a') as f: f.write('end hello python') def test1(): print ('test1 starting action...') with open('a.txt', 'a') as f: f.write('end hello python') def test2(): print ('test2 starting action...') with open('a.txt', 'a') as f: f.write('end hello python')
但是用函数来代替重复的代码段
def log(): #把逻辑写成函数 with open('a.txt','a') as f: f.write('end??? hello python') def test1(): print ('test1 starting action...') log() #调用函数 def test2(): print ('test2 starting action...') log() test1() test2()
再次优化,给日志加上时间
import time def log(): #把逻辑写成函数 time_format = '%Y-%m-%d %X' #时间格式 time_current = time.strftime(time_format) with open('a.txt','a') as f: f.write('time %s hello python'%time_current) def test1(): print ('test1 starting action...') log() #调用函数 def test2(): print ('test2 starting action...') log() test1() test2()
函数的三大优点
代码重用
保持一致性
可扩展性
2. 函数和过程:
过程定义:过程就是 简单特殊没有返回值的函数
之前的函数都没有返回值,但是在python中,没有返回值,python解释器会隐式的返回None,所以在python中即便是过程也可以算作函数。
def test01(): msg='hello ' print(msg) def test02(): msg='hello MR.shu' print(msg) return msg t1 = test01() t2 = test02() print('form test01 return is [%s]'%t1) print('from test02 return is [%s]'%t2)
输出为:
hello
hello MR.shu
form test01 return is [None]
from test02 return is [hello MR.shu]
浙公网安备 33010602011771号