一、作为运算符
*表示乘法运算
**表示乘方运算
print(f"a = {3 * 2}") # 输出6
print("b = {}".format(3 ** 2)) # 输出9
二、作为函数形参
*在python中做函数形参,表示的是一个可变长度的序列,类型为tuple,即将所有参数放入一个元组(tuple)中,被函数使用。
**在python中做函数形参,表示的是一个可变长度的序列,类型为dict,即将所有的关键字参数,放入一个字典(dict)中, 被函数使用。
*与**作为形参同时出现时,**必须在最后面
def printx(*arg1, **arg2):print("arg1={0}, type:{1}".format(arg1, type(arg1)))print("arg2={0}, type:{1}".format(arg2, type(arg2)))P1 = printx(1, 2, key1=1, key2=2) ## 此时1, 2 即为*arg1; key1=1, key2=2 即为**arg2
#output
#arg1=(1, 2), type:<class 'tuple'>
#arg2={'key1': 1, 'key2': 2}, type:<class 'dict'>
三、作为函数实参
在list/tuple/set前加*,会把序列中的所有元素解包成位置参数
在dict前加*,会把dict的键变成位置参数;加**,把字典的键值对变成关键字参数。
A = (a,b,c)
B = {“key1” :1, “key2”:2}
P3 = Printx(*A) # 等同于printx(a,b,c)
P3 = Printx(*A, *B) #等同于printx(a,b,c,key1,key2)
P3 = Printx(*A, **B) #等同于printx(a,b,c,key1=1,key2=2)
def printx(*arg1, **arg2):print("arg1={0}, type:{1}".format(arg1, type(arg1)))print("arg2={0}, type:{1}".format(arg2, type(arg2)))#arg1={0}中的0对应的是format 里面的变量arg1 ,如果将0换成1 即arg1={1},此时arg1={1}中的1对应的是format 里面的变量type(arg1);A = (1, 2, 3)
K1 = {'key1': 1, 'key2': 2}
P2 = printx(*A, *K1) # 注意在dict前加一个*,只把dict的 '键' 作为位置参传递
print('')
P3 = printx(*A, **K1) # 此时 #output
#arg1=(1, 2, 3, 'key1', 'key2'), type:<class 'tuple'>
#arg2={}, type:<class 'dict'>#arg1=(1, 2, 3), type:<class 'tuple'>
#arg2={'key1': 1, 'key2': 2}, type:<class 'dict'>
四、作为序列解包
注意序列解包时*解包为list,不再是tuple了
- 先对不带的变量解包,剩余的数据在划分给带的变量
x,y,*z = 1,2,3,4,5 #等同于 x=1, y = 2, z= [3,4,5]
x,*y,z = 1,2,3,4,5 #等同于 x=1, y = [2,3,4], z= 5 - 如果左值比右值要多,那么带 * 的变量默认为空列表
x,y,*z = 1,2 #等同于 x=1, y = 2, z= []
x,*y,z = 1,2 #x=1, y = [], z= 2 - 单*只解包dict的键, **解包dict键值对
key_A = {‘key1’:1, ‘key2’:2}
key_B = {“key3” :3, “key4”:4}
X = {*key_A} #等同于x= {‘key1’, ’key2’}
X = {**key_A} #等同于x= {‘key1’:1, ‘key2’:2}
X = {**key_A, **key_B} #等同于组包,x={‘key1’:1, ‘key2’:2, “key3” :3, “key4”:4}
注意:
在Python中默认的函数参数顺序是:必选参数、默认参数、*args和**kwargs。如下所示:
def testFunc(name, age=10, *agrs, **kwargs):pass