python:函数

#!usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = "Samson"

def test(x,y=3):#默认参数,调用函数时,默认参数可传可不传
print(x,y)
test(2)
test(2,3)#位置参数,与形参顺序一一对应
test(y=3,x=2)#关键参数,与形参顺序无关
#test(2,x=2)#错误
#test(x=2,3)#错误,关键参数是不能写在位置参数前边的
#test(y=2,3)#错误
def test1(x,*name):#将传递的位置参数作为一个元组
print(name)
test1(1,2,3,4,5)
test1(1,*[1,2,3,4,5])#与上面是等同的

def test2(**name):#将传递的关键字参数作为字典
print(name)
test2(name="sun",sex="man")
test2(**{'name': 'sun', 'sex': 'man'})

def test3(name,age=18,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
test3("alex",age=34,sex="m",hobby="tesla")#其中元祖*args没有传递位置参数


高阶函数:
变量可以指向函数(通过返回值),函数的参数能接受变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
def add(x,y,f)
  return f(x)+f(y)
res = add(-1,3,abs)
print(res)

匿名函数:
calc = lambda x:x*3
calc(3)




原文地址:https://www.cnblogs.com/cansun/p/8060273.html