python * ** 操作符

mac2026-03-30  6

1、* 操作符后面跟的是元组或列表,**后面跟的是字典

2、调用函数时,* 或 ** 用于将元组或字典拆分并作为独立的函数参数传递

*tuple_arg 将 [1, 2] 拆解为独立的位置参数 1,2,**kw_arg将 {‘c’:5, ‘d’:6} 拆解为独立的关键字参数传递,test_args(*tuple_arg, **kw_arg) 等价于 test_args(1, 2, c=5, d=6)

def test_args(a,b,c,d): print a,b,c,d # output:1 2 5 6 tuple_arg = [1,2] kw_arg = {'c':5, 'd':6} test_args(*tuple_arg, **kw_arg)

3、定义函数时,* 或 ** 用于压缩被传递到函数中的参数到元组或字典中,用于参数个数未知的情况

从输出可以看到,参数1,2被压缩到了元组tp中,c=5,d=6被压缩到了字典kv中

def test_args(*tp, **kv): print 'tp is ', tp print 'kv is ', kv test_args(1, 2, c=5, d=6) # output: # tp is (1, 2) # kv is {'c': 5, 'd': 6}

3、* 或 ** 还有很多其他用法,有的用法只在python 3中支持,具体见 python中星号的本质及其使用方法

最新回复(0)