函数是可以被引用的(访问或者以其他变量作为其别名),也作为参数传入参数,以及作为列表和字典等容器对象的元素函数有一个独一无二的特征使它同其他对象区分开来,那就是函数是可调用的,
所有必需的参数都要在默认参数之前。
Python允许执行一个没有显式定义参数的函数,相应的方法是通过一个把元组(非关键字参数)或字典(关键字参数)作为参数组传递给函数。
func(*tuple_grp_nonkw_args, **dict_grp_kw_args)
函数属性是Pyhton另外一个使用了句点属性标识并拥有名称空间的领域。
def foo():
'foo() -- properly created doc string'
def bar():
pass
bar.__doc()__ = 'Oops, forgot the doc str above'
bar.version = 0.1
可变长度的参数元组必须在位置和默认参数之后,带元组(或者非关键字可变长参数)的函数普遍的语法如下:
def function_name([formal_args,]*vargs_tuple):
'function_documentatiom_string'
function_body_suite
def tupleVarArgs(arg1, arg2 = 'defaultB', *theRest):
'display regular args and non-keyword variable args'
print 'formal arg 1:', arg1
print 'formal arg 2:', arg2
for eachXtrArg in theRest:
print 'another arg:', eachXtrArg
tupleVarArgs('abc', 123, 'xyz', 456.789)
def function_name([formal_args,][*vargst,] **vargsd):
'function_documentatiom_string'
function_body_suite
def dictVarArgs(arg1, arg2 = 'defaultB', **theRest):
'display2 regular args and keyword variable args'
print 'formal arg 1:', arg1
print 'formal arg 2:', arg2
for eachXtrArg in theRest.Keys():
print 'Xtra arg %s: %s' \
% (eachXtrArg, str(theRest[eachXtrArg])
dictVarArgs('one', d = 10, e = 'zoo', men = ('freud', 'gaudi'))
关键字和非关键字可变长参数都有可能用在同一个函数中,只要关键字字典是最后一个参数并且非关键字元组先于它之前出现。
摘自《Python核心编程》