python 中参数传递 * 和 ** 的问题

python 中参数传递 * 和 ** 的问题,以 tuple和dict方式传递参数

 
 
在python中,有时会看到这样的函数定义:
    def   p1(*arg1,**arg2):
          pass
也有看到这样的函数调用:
    i=5
    function(*i)
这些都是什么意思呢?
1.传入的参数生成 tuple 和 dict
      def    p1(*a1,**a2):
             print a1,'/n',a2
       p1(1,2,3,4,arg5=5,arg6=6)
       结果为:
       (1,2,3,4)
       {'arg5':5,'arg6':6}
2.传入的tuple 或 dict解析成参数序列
    def   q1(arg1,arg2,arg3,arg4):
          print arg1,arg2,arg3,arg4
    tu=(1,2,3,4)
    print 'extract from tuple /n'
    q1(*tu)

    di={'arg1':1,'arg2':2,'arg3':3,'arg4':4}
    print '/nextract from dict /n'
    q1(**di)
    结果为:
    extract from tuple
    1234
    extract from dict
    1234
它们是互逆过程,在需要传递函数和函数参数的时候很有用
如:
    def    worker1(arg1):
          print arg1
    def    worker2(arg1,arg2):
          print arg1,arg2
    def   calling(callable,arg):
          callable(*arg)
if __name__="__main__":
    calling(worker1,(1,))
    calling(worker2,(1,2))
posted @ 2018-03-27 17:35  luna1  阅读(150)  评论(0编辑  收藏  举报