python中包含四种函数:全局函数、局部函数、lambda函数、方法。python
局部函数:定义在其余函数以内。ide
lambda函数:表达式。函数
方法:与特定数据类型关联的函数spa
使用序列拆分操做符(*)来提供位置参数。orm
例如函数heron的参数存放于一个列表sides中,能够:heron(sides[0],sides[1],sides[2]) 也能够进行拆分:heron(*sides)。若是列表包含比函数参数更多的项数,就能够使用分片提取出合适的参数。blog
在使用可变数量的位置参数的函数时,可以使用序列拆分操做符。it
>>> def product(*args): result = 1 for arg in args: result *= arg return result >>> product(1,2,3,4) 24 >>> product(5,3) 15
能够将关键字参数放在位置参数后面,即def sum_of_power(*args,poewer=1):...io
* 自己做为参数:代表在*后面不该该再出现位置参数,但关键字参数是容许的:def heron(a,b,c,*,unit="meters"):.....form
若是将* 做为第一个参数,那么不容许使用任何位置参数,并强制调用该函数时使用关键字参数:def print_set(*,paper="Letter",copies=1,color=False):...。能够不使用任何参数调用print_set(),也能够改变某些或所有默认值。但若是使用位置参数,就会产生TypeError异常,好比print_set(“A4”)就会产生异常。class
映射拆分操做符(**)
** 用于对映射进行拆分。例如使用**将字典传递给print_set()函数:
options = dict(paper="A4",color=True)
pritn_set(**options)
将字典的键值对进行拆分,每一个键的值被赋予适当的参数,参数名称与键相同。
在参数中使用**,建立的函数能够接受给定的任意数量的关键字参数:
>>> def add_person_details(ssn,surname,**kwargs): print "SSN=",ssn print " surname=",surname for key in sorted(kwargs): print " {0}={1}".format(key,kwargs[key]) >>> add_person_details(123,"Luce",forename="Lexis",age=47) SSN= 123 surname= Luce age=47 forename=Lexis >>> add_person_details(123,"Luce") SSN= 123 surname= Luce
举例:
>>> def print_args(*args, **kwargs): for i,arg in enumerate(args): print "positional argument{0}={1}".format(i,arg) for key in kwargs: print "keyword argument{0}={1}".format(key,kwargs[key]) >>> print_args(['a','b','c','d'],name='Tom',age=12,sex='f') positional argument0=['a', 'b', 'c', 'd'] keyword argumentage=12 keyword argumentname=Tom keyword argumentsex=f