1.函数和函数式变成
函数的定义
初中数学函数的定义:一般的,在一个变化过程中,如果两个变量x和y,并且对于x的每一个确定值,y都有唯一确定的值于其对应,那么我们就把x称之为自变量,把y称为因变量,y是x的函数。自变量x的取值范围叫做这个函数的定义域
编程语言中函数定义:函数式逻辑结构化和过程化的一中编程方法。
def test(x) '''The function definitions''' x+=1 return x def :定义函数的关键字 test:函数名 ():内科定义形参 ''' 文件描述 ''':文件描述 (非必要,但是强烈建议为你的函数添加描述信息) x+=1:泛指代码块或程序处理逻辑 return:定义返回值
补充:
函数式编程:先定义一个数学函数,然后按照这个数学模型用编程语言去实现它。
为何使用函数:
没有函数的编程只是在写逻辑(功能),想要脱离函数,重用你的逻辑,唯一的方法就是拷贝
例一:
#假如我们编写好了一个逻辑(功能),用来以追加的方式写日志: with open('a','a',encoding='utf-8')as f: f.write('end action') ''' 现在有三个函数,每个函数在处理完自己的逻辑后,都需要使用上面这个逻辑, 那么唯一的方法就是,拷贝三次这段逻辑 ''' def test1(): print('test1 satarting action') with open('a', 'a', encoding='utf-8')as f: f.write('end action\n') def test2(): print('test2 satarting action') with open('a', 'a', encoding='utf-8')as f: f.write('end action\n') def test3(): print('test3 satarting action') with open('a', 'a', encoding='utf-8')as f: f.write('end action\n') #那么假设有>N个函数都需要使用这段逻辑,你可以拷贝N次吗?
例二:
优化后的代码
def logger(): with open('a','a',encoding='utf-8')as f: f.write('end action') def test1(): print('test1 satarting action') logger() def test2(): print('test2 satarting action') logger() def test3(): print('test3 satarting action') logger()
例三:
需求变了(让我们来为日志加上时间吧)
import time time_format='%Y-%m-%d-%X' time_current=time.strftime(time_format) def logger(): with open('a','a',encoding='utf-8')as f: f.write('%s end action\n'%time_current) def test1(): print('test1 satarting action') logger() def test2(): print('test2 satarting action') logger() def test3(): print('test3 satarting action') logger() test1() test2() test3()
总结例二和例三可概括使用函数的三大优点
1.代码的重用
2.保持一致性
3.可扩展性