【Python基础】Python星号*与**用法分析

1. 加了星号(*)的变量名会存放所有未命名的变量参数,不能存放dict,否则报错,收集其余位置的参数,如果不提供任何收集的元素给星号,就是一个空元组。

如:

?
1
2
3
4
5
6
7
def multiple(arg, * args):
   print "arg: " , arg
   #打印不定长参数
   for value in args:
     print "other args:" , value
if __name__ = = '__main__' :
   multiple( 1 , 'a' , True )

输出:

2. 加了星号(**)的变量名会存放所有未命名的变量参数,收集其余带有关键字参数的,如果不提供任何收集的元素给**,就是一个字典。

?
1
2
3
4
5
6
def multiple2( * * args):
   #打印不定长参数
   for key in args:
     print key + ":" + bytes(args[key])
if __name__ = = '__main__' :
   multiple2(name = 'Amy' , age = 12 , single = True )

输出

3. 有 *args 和 **dictargs:

?
1
2
3
4
5
6
7
8
9
10
def multiple(arg, * args, * * dictargs):
   print "arg: " , arg
   #打印args
   for value in args:
     print "other args:" , value
   #打印dict类型的不定长参数 args
   for key in dictargs:
     print "dictargs:" + key + ":" + bytes(dictargs[key])
if __name__ = = '__main__' :
   multiple( 1 , 'a' , True , name = 'Amy' ,age = 12 , )

输出:

另外,在Python数学运算中*代表乘法,**为指数运算,示例代码如下:

?
1
2
3
4
5
>>> 2 * 4
8
>>> 2 * * 4
16
>>> 

下面主要说一下参数收集的逆过程,也就是方法定义中并没有星号,但是在调用方法的时候携带了星号作用是什么?

看个例子:

def addxy):
    print x+y
para =  (1,2)
add(*para)

打印结果为: 3, 可见在调用参数的时候使用*号可以自动解包。 
同理如果是两个星号的话,就是带有**号的字典,自动解包。

def add(x,y):
    print x+y
kkwd = {'x' :1,'y':2}
add(**kkwd)

打印结果为: 3, 可见在调用参数的时候使用*号可以自动解包。

(*) 星号的参数传递主要是在不知道参数多少的情况下可以准确的传递参数


猜你喜欢

转载自blog.csdn.net/wangpengfei163/article/details/80539227
今日推荐