标签:
计算xn的函数:
1 def power(x, n=2): 2 s = 1 3 while n > 0: 4 n = n - 1 5 s = s * x 6 return s
设置默认参数时,有几点要注意:
例 传入一个list,添加一个END
再返回:
1 def add_end(L=[]): 2 L.append(‘END‘) 3 return L
>>> add_end() [‘END‘] >>> add_end() [‘END‘, ‘END‘] >>> add_end() [‘END‘, ‘END‘, ‘END‘]
如何修改:
def add_end(L=None): if L is None: L = [] L.append(‘END‘) return L
编写程序时,尽量设计成不变对象。
在函数内部,可变参数numbers
接收到的是一个tuple;调用该函数时,可以传入任意个参数。
1 def calc(*numbers): 2 sum = 0 3 for n in numbers: 4 sum = sum + n * n 5 return sum
在list或tuple前面加一个*
号,把list或tuple的元素变成可变参数传进去:
1 >>> nums = [1, 2, 3] 2 >>> calc(*nums) 3 14
**kw
是关键字参数,kw接收的是一个dict
1 def person(name, age, **kw): 2 print ‘name:‘, name, ‘age:‘, age, ‘other:‘, kw
先组装出一个dict,然后,把该dict转换为关键字参数传进去:
1 >>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘} 2 >>> person(‘Jack‘, 24, **kw) 3 name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
参数定义的顺序必须是:必选参数、默认参数、可变参数和关键字参数
1 def func(a, b, c=0, *args, **kw): 2 print ‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw
通过个tuple和dict调用:
1 >>> args = (1, 2, 3, 4) 2 >>> kw = {‘x‘: 99} 3 >>> func(*args, **kw) 4 a = 1 b = 2 c = 3 args = (4,) kw = {‘x‘: 99}
标签:
原文地址:http://www.cnblogs.com/utopia8/p/5130850.html