在函数调用中,星号的使用。
对字符串进行传递
def fun(x,y):
print(x+y)
s = 'b'
fun(*s)
执行结果
fun(*s)
TypeError: fun() missing 1 required positional argument:
'y'
未能成功进行传递,因为缺省一个参数'y'
def fun(x,y):
print(x+y)
s = 'ab'
fun(*s)
执行结果
ab
成功的传递,*s 表示一个迭代序列中的元素
def fun(x,y):
print(x+y)
s = 'abc'
fun(*s)
执行结果
fun(*s)
TypeError: fun() takes 2 positional arguments but 3 were
given
字符串s
中有三个元素,那么这个迭代序列就会有三个迭代对象,作为参数传入这个函数中,多出了一位参数。无法成功传递。
def fun(x,y):
print(x+y)
s = 'ab'
fun(**s)
执行结果
TypeError: fun() argument after ** must be a mapping(映射), not
str
--------------------------------------------------------------------------------------
对元组进行传递
def fun(x,y):
print(x+y)
tu = (1)
fun(*tu)
执行结果
fun(*tu)
TypeError: fun() argument after * must be an iterable(迭代对象),
not int
def fun(x,y):
print(x+y)
tu = (1,2)
fun(*tu)
执行结果
3
元组tu 中有两个元素,*tu 代表两个迭代对象,同时传入函数中作为实际参数。传递成功
def fun(x,y):
print(x+y)
tu = (1,2)
fun(**tu)
执行结果
fun(**tu)
TypeError: fun() argument after ** must be a mapping(映射), not
tuple
-------------------------------------------------------------------------------
对字典进行传递
def fun(x,y):
print(x+y)
di = {'a':1,'b':2}
fun(*di)
执行结果
ab
字典中迭代的对象是字典的键,同时传入函数作为实参
def fun(x,y):
print(x+y)
di = {'a':1,'b':2}
fun(**di)
执行结果
fun(**di)
TypeError: fun() got an unexpected keyword argument 'a'
需要映射的对象分别是x和y ,所以字典的键必须是字符x和y
def fun(x,y):
print(x+y)
di = {'x':1,'y':2}
fun(**di)
执行结果
3
字典中的键必须对应形参,并且将键映射的值进行传递,并作为实参进行调用。
--------------------------------------------------------------
在不定长参数的传递中表现
def fun(x,*y,**z):
print(x)
print(y)
print(z)
tu = (1,('a','b'),{3:'c'})
dic = {'z':1}
fun(tu,tu,**dic)
执行结果
(1, ('a', 'b'), {3: 'c'})
((1, ('a', 'b'), {3: 'c'}),)
{'z': 1}
参数传递
x = tu 第一个形参x 调用第一个tu 的对象
*y 是代表一个元组的迭代对象,所以tu的对象作为y元组的一个迭代对象。所以tu 元组只是y
元组中的一个元素。元组中的元素可以是多个的
**z 是代表一个字典的映射,所以**dic 也是一个字典的映射,将它传输给**z,z = dic
。字典中的映射是可以是多个的,字典的映射还可以通过将字符进行赋值的形式出现。
def fun(x,*y,**z):
print(x)
print(y)
print(z)
tu = (1,('a','b'),{3:'c'})
dic = {'z':1}
fun(*tu,tu,**dic,d = 2)
执行结果
1
(('a', 'b'), {3: 'c'}, (1, ('a', 'b'), {3: 'c'}))
{'z': 1, 'd': 2}
参数传递
*tu 是一个迭代对象。元组tu 中有三个元素1,('a','b'),{3:'c'}
,它们传入函数内,会首先将形参x 进行传递,剩下的给元组*y 进行传递;形式参数x
不一定只能是数字,还可以是别的数据类型
映射部分数据都是传递给字典的映射的。
def fun(x,*y,**z):
print(x)
print(y)
print(z)
tu = (('a','b'),{3:'c'})
dic = {'z':1}
fun(*tu,tu,**dic,d = 2)
执行结果
('a', 'b')
({3: 'c'}, (('a', 'b'), {3: 'c'}))
{'z': 1, 'd': 2}
def fun(x,*y,**z):
print(*x)
print(*y)
print(*z)
tu = (('a','b'),{3:'c'})
dic = {'z':1}
fun(*tu,tu,**dic,d = 2)
执行结果
a b
{3: 'c'} (('a', 'b'), {3: 'c'})
z d