# 2.默认参数

L.append(‘End’)
return L

[‘End’]

[‘End’, ‘End’]
[‘End’, ‘End’, ‘End’]

``````def add_end(L=None):
if L is None:
L = []
L.append('END')
return L

['End']
['End']
``````

# 3.可变参数

``````def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
>>>calc([1,2,3])
14
>>>calc([])
0
``````

``````def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n*n
return sum
>>>calc(1,2,3)
14
>>>calc()
0
``````

``````list1 = [1,2,3]
>>>calc(*list1)
14
``````

# 4.关键字参数

``````test.py:
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)

extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Tom', 40)
person('Jack', 25, city='Beijing', job = 'Engineer')
person('Jack', 25, **extra)

iTerm终端：
>>>python3 ~/python_test/test.py
name: Tom age: 40 other: {}
name: Jack age: 25 other: {'city': 'Beijing', 'job': 'Engineer'}
name: Jack age: 25 other: {'city': 'Beijing', 'job': 'Engineer'}

``````

# 5.命名关键字参数

``````test.py:
def person(name, age, **kw):
if 'city' in kw:
print("there is a 'city' key")
if 'job' in kw:
print("there is a 'job' key")
print('name:', name, 'age:', age, 'other:', kw)

extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Tom', 40)
person('Jack', 25, **extra)

iTerm终端：
>>>python3 ~/python_test/test.py
name: Tom age: 40 other: {}
there is a 'city' key
there is a 'job' key
name: Jack age: 25 other: {'city': 'Beijing', 'job': 'Engineer'}
``````

``````def person(name, age, *, city, job):
print(name, age, city, job)
``````

``````>>>person('Jack', 25, city='Beijing', job = 'Engineer')
Jack 25 Beijing Engineer
``````

``````# ~/python_test/test.py
def person(name, age, \*args, city, job):
print(name, age, args, city, job)
person('Jack', 24, 'Beijing', 'Engineer')
``````

``````>>>python3 ~/python_test/test.py
Traceback (most recent call last):
File "/Users/lijing/python_test/test.py", line 4, in <module>
person('Jack', 25, 'Beijing', 'Engineer')
TypeError: person() missing 2 required keyword-only arguments: 'city' and 'job'
``````

``````def person(name, age, *, city = 'Beijing', job):
print(name, age, city, job)
``````

# 6.参数组合

``````# ~/python_test/test.py
def f1(a, b, c=0, *args, **kw):
print(a, b, c, args, kw)
def f2(a, b, c=0, *, d, **kw):
print(a, b, c, d, kw)
args = {1, 2, 3}
kw = {'d':99, 'x':'#'}

f1(1,2)
f1(1,2,c=3)
f1(1,2,3,'a','b')
f1(1,2,3,'a','b',x=99)
f2(1,2,d=99,ext=None)
f1(*args, **kw)
f2(*args, **kw)

#iTerm2终端:
>>>python3 ~/python_test/test.py
1 2 0 () {}
1 2 3 () {}
1 2 3 ('a', 'b') {}
1 2 3 ('a', 'b') {'x': 99}
1 2 0 99 {'ext': None}
1 2 3 () {'d': 99, 'x': '#'}
1 2 3 99 {'x': '#'}
``````
原文作者：晶爷传说
原文地址: https://www.jianshu.com/p/3a6d610454d7
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。