码迷,mamicode.com
首页 > 其他好文 > 详细

函数与函数式编程

时间:2018-07-22 17:04:50      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:没有   st3   不能   ogg   add   tuple   面向   函数式编程   调用   

#面向对象:特点:类(class)
#面向过程:过程(def)
#函数式编程:函数(def)

#定义函数:
def func1():#
"""test...."""
print(‘in the func1‘)
return 0

#定义过程
def func2()
"""test2.........."""
print(‘in the func2‘)

#调用1,x=func1();y=func2()
#过程和函数都可以调用,过程就是没有返回值的函数。
# 面向过程的程序设计方法就是用一个个def定义的过程拼接在一起。把一段段逻辑,一段段功能包含到一个def定义的过程中,用的时候调用
#定义函数三大优点:代码重用,减少重复代码;保持一致;可扩展性
def test1():
print(‘in the test1‘)

def test2():
print(‘in the test2‘)
return 0
def test3():
print(‘in the test3‘)
#return 1,‘hello‘,[‘alex‘,‘wupeiqi‘],{‘name‘:‘alex‘}
return test2#可以return,test2
x=test1()
y=test2()
z=test3()
print(x)
print(y)
print(z)
#返回值数=0:返回none
#返回值数=1:返回object
#返回值数>1:返回tuple(一个元组,return的多个值撞到一个元组中)
#为什么要返回值:因为需要一个执行结果,后续程序可能需要根据其结果进一步操作

#——————————————————————有参数的函数--------------------------------------------------------
def test(x,y,z):
print(x)
print(y)
print(z)
# test(y=2,x=1) #关键字调用,与形参顺序无关
# test(1,2) #位置参数调用,与形参一一对应,1,2是实参,x,y是形参
#test(x=2,3)
test(3,z=2,y=6)#关键字和位置参数同在,以位置调用为首标准。关键参数是不能写在位置参数前面的!!


#-----------------------------------------------------------------------------------------------
#*args:接受N个位置参数,转换成元组形式
# def test(*args):
# print(args)
#
# test(1,2,3,4,5,5)
# test(*[1,2,4,5,5])# args=tuple([1,2,3,4,5])

# def test1(x,*args):
# print(x)
# print(args)
#
# test1(1,2,3,4,5,6,7)


#**kwargs:接受N个关键字参数,转换成字典的方式
# def test2(**kwargs):
# print(kwargs)
# print(kwargs[‘name‘])
# print(kwargs[‘age‘])
# print(kwargs[‘sex‘])
#
# test2(name=‘alex‘,age=8,sex=‘F‘)
# def test3(name,**kwargs):
# print(name)
# print(kwargs)
#
# test3(‘alex‘,age=18,sex=‘m‘)

# def test4(name,age=18,**kwargs):
# print(name)
# print(age)
# print(kwargs)
#
# test4(‘alex‘,age=34,sex=‘m‘,hobby=‘tesla‘)

def test4(name,age=18,*args,**kwargs):#参数组一定放在后面
print(name)
print(age)
print(args)
print(kwargs)
logger("TEST4")

def logger(source):
print("from %s" % source)

test4(‘alex‘,age=34,sex=‘m‘,hobby=‘tesla‘)

#---------------------------------------------------高阶函数------------------------------------------------------
#变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
def add(a,b,f):#等于把f替换成abs
return f(a)+f(b)
res=add(3,-6,abs)
print(res)

函数与函数式编程

标签:没有   st3   不能   ogg   add   tuple   面向   函数式编程   调用   

原文地址:https://www.cnblogs.com/wangchu/p/9350107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!