Python笔记(19)函数与函数式编程

    技术2026-03-19  9

    #!/user/bin/env python # -*- coding:utf-8 -*- # author:berlin # 1、3种编程方法: # (1)面向对象---->核心内容是:类------>class # (2)面向过程---->核心内容是:过程------>def # (3)函数式编程----->核心内容是:函数------>def # 2、函数的定义: # (1)初中教学时的函数定义是:一般的,在一个变化过程中,如果有两个变量x和y,并且对于x的每一个确定的值,y都有 # 唯一的值与其对应,那么我们就把x称之为自变量,把y称之为因变量,y是x的函数,自变量x的取值范围叫做这个函数的定义域。 # (2)编程语言中函数的定义是:函数是逻辑结构化和过程化的一种编程方法。 # python中函数定义方法: # def test(x): # def代表函数的关键字;test代表函数名;()代表括号内可定义形参 # '这是函数定义' # ‘’指文档描述(非必要,但是强烈建议为你的函数添加描述信息) # x += 1 # 泛指代码块或程序处理逻辑 # return x # 定义返回值 # # # # 3、面向过程与函数式编程的区别?(定义过程和定义函数的区别?) # # (1)函数案例: # def function1(): # '定义函数的案例' # print('定义函数') # return 0 # # # # (2)过程案例: # def function2(): # '定义过程的案例' # print('定义过程') # # # # (3)分别调用函数和过程,并输出: # a = function1() # b = function2() # print('函数返回的值是:%s' % a) # print('过程返回的值是:%s' % b) # (4)故,函数和过程的区别在于函数有return,而过程没有return。在python中,函数和过程没有很明确的界限, # 因为过程虽然没有return,但是pyton隐形的给过程返回了None。 # 4、为什么要使用函数? # (1)例1: # 假设我们编写好了一个逻辑(功能),用未以追加的方式写日志: # with open('a.txt', 'ab') as f: # f.write('end action') # # # 现在有3个函数,每个函数在处理完自己的逻辑后,都需要调用上面的逻辑,那么唯一的方法就是:拷贝3次这段逻辑。 # def test1(): # print('test1 starting action...') # with open('a.txt', 'ab') as f: # f.write('end action') # # def test2(): # print('test2 starting action...') # with open('a.txt', 'ab') as f: # f.write('end action') # # def test3(): # print('test3 starting action...') # with open('a.txt', 'ab') as f: # f.write('end action') # 那么假设有N个函数,你就拷贝N次吗?--------------显然不可能的!!! # (2)例2: # 把例1优化后: # def logger_test(): # with open('a.txt', 'ab') as f: # f.write('end action') # # def test1(): # print('test1 starting action...') # logger_test() # # def test2(): # print('test2 starting action...') # logger_test() # # def test3(): # print('test3 starting action...') # logger_test() # (3)例3: # 需求增加:为日志加上时间~ import time #使用时间库 def logger_test(): time_format = '%Y-%m-%d %X' #定义时间格式,‘年月日小时’ time_current = time.strftime(time_format) #指明按照定义的时间格式显示时间 with open('a.txt', 'a+') as f: f.write('%s end action\n' %time_current) def test1(): print('test1 starting action...') logger_test() def test2(): print('test2 starting action...') logger_test() def test3(): print('test3 starting action...') logger_test() # 调用输出: test1() test2() test3() # 故,为什么要用函数?使用了函数有什么好处?在例1和例2可以看出函数具有“代码重用”的好处。 # 在例2和例3又可以看出函数具有“保持一致性”、“可扩展性”的好处。 # (1)代码重用 # (2)保持一致性 # (3)可扩展性
    Processed: 0.014, SQL: 9