码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-03-27 18:46:56      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:name   csdn   click   mod   extra   lin   pass   序列   定义   

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))

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

标签:name   csdn   click   mod   extra   lin   pass   序列   定义   

原文地址:https://www.cnblogs.com/lullaby-suede/p/8658772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!