一、自定义函数参数
1.种类
(1)位置参数
"x"就是位置参数
#!/usr/bin/env python # -*- coding: utf-8 -*- #author: dingkai #mtime: 2018/4/27 def power(x): result = x * x print(result)
(2)默认参数
"n"就是默认参数
#!/usr/bin/env python # -*- coding: utf-8 -*- #author: dingkai #mtime: 2018/4/27 def power(x,n=1): s = 1 while n > 0: n = n - 1 s = s * x return s
(3)可变参数
"numbers"就是可变参数,调用calc函数时,变元numbers是一个列表
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
print(calc([1,2,3]))
(4)关键字参数
"**every"是关键字参数
def person(name,age,**every):
print(‘name:‘,name, ‘age:‘,age, ‘other:‘, every)
extra = {‘city‘:‘Beijing‘, ‘job‘:‘OPS‘}
#person(‘dingkai‘,25,city = extra[‘city‘],job = extra[‘job‘])
#person(‘dingkai‘,25,**extra)
(5)命名关键字参数
"*"后面的就是命名关键字
def person(name,age,*,city,job): print(name,age,city,job) #person(‘dinkai‘,26,city=‘Beijing‘,job=‘OPS‘)
2.注意事项:
(1)是必选参数在前,默认参数在后,否则Python的解释器会报错(思考一下为什么默认参数不能放在必选参数前面);
(2)是如何设置默认参数。
原文:https://www.cnblogs.com/dingkailinux/p/8963652.html