python函数与函数式编程

2022-08-1122:55:18编程语言入门到精通Comments1,020 views字数 1010阅读模式

1、函数与函数式编程介绍文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

在过去,大家广为熟知的编程方式无非就两种:面向对象和面向过程,不论是哪一种,它们都是编程的一种规范或者是如何编程的方法论。而现在,一种更为古老的编程方式:函数式编程,以其不保存状态,不修改变量等特性重新进入我们的视野。下面就一起了解一下这一传统的编程理念。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

python函数与函数式编程文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

函数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html


2、面向对象和面向过程文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

  • 面向对象---》类---》class
  • 面向过程---》过程---》def
  • 函数式编程---》函数---》def

函数和过程都是可以调用的实体,不同:过程就是没有返回值的函数而已,函数有返回值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

A、定义一个函数
def func1():
	"""test1"""
	print('in the func1')
	return 0

#调用函数
x=func1()
————————————————
B、定义一个过程
def func2():
	"""test2"""#文档描述
	print('in the func2')
	
#调用过程
y=func2()

print('from func1 return is %s' %x)
print('from func2 return is %s' %y)

运行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

in the func1
in the func2
from func1 return is 0
from func2 return is None

3、编程语言中函数定义:函数是逻辑结构化和过程化的一种编程方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

python函数与函数式编程文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

函数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

4、为什么要使用函数文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

  • 可重复利用,提高代码可用性
  • 可扩展性
  • 一致性
import time

def log():
	time_format='%Y-%m-%d %X'
	time_current=time.strftime(time_format)
	with open('log.txt','a+')as f:
		f.write('%s end action\n' %time_current)

def test1():
	print('test1 starting action...')

	log()
def test2():
	print('test2 starting action...')

	log()
def test3():
	print('test3 starting action...')

	log()

test1()
test2()
test3()

运行结果:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html

end action
end action
end action
2019-01-28 15:50:54 end action
2019-01-28 15:50:54 end action
2019-01-28 15:50:54 end action
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/26996.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/26996.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定