1、参数 统一 个数
code
def t1(x,y):
print(x,y)
#调用函数的时候,参数多了少了,报错
t1(1,2,3)
打印
Traceback (most recent call last):
File "E:/workspace/python/sk14/day03/07_function7.py", line 7, in
t1(1,2,3)
TypeError: t1() takes 2 positional arguments but 3 were given
2、可传递至少0个参数
code
def t2(*args):
print(args)
#多参数
t2(1,2,3)
t2(*[1,2,3])
t2(1,2)
t2(1)
t2()
打印
(1, 2, 3)
(1, 2, 3)
(1, 2)
(1,)
()
3、至少有 1 个参数
code
def t3(x,*args):
print(x)
t3(1,2,3,4)
t3(1,2,3)
t3(1,2)
t3(1)
打印
1
1
1
1
4、字典参数**kwargs
code
def t4(**kwargs):
print(kwargs)
t4(name='alex',age='8',sex='f')
t4(**{'name':'alex','sex':'女','age':'8'})
打印
{'name': 'alex', 'age': '8', 'sex': 'f'}
{'name': 'alex', 'sex': '女', 'age': '8'}
5、混合参数1
code
def t5(name,age=18,**kwargs):
print(name)
print(age)
print(kwargs)
t5('heihouzi',sex='m',hobby='tesla')
t5('heihouzi',sex='m',hobby='tesla',age=43)
打印
heihouzi
18
{'sex': 'm', 'hobby': 'tesla'}
heihouzi
43
{'sex': 'm', 'hobby': 'tesla'}
6、混合参数2
code
def t6(name,age=18,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
t6("heihouzi",4,5,6,sex='m',hobby='tesla')
打印
heihouzi
4
(5, 6)
{'sex': 'm', 'hobby': 'tesla'}
7、嵌套函数
code
def t7(name):
loggers(name)
def loggers(n):
print("from %s" % n)
t7("heihouzi")
打印
from heihouzi