• python参数中的*和**


    问题:
         Python的函数定义中有两种特殊的情况,即出现*,**的形式。
         如:def myfun1(username, *keys)或def myfun2(username, **keys)等。

    解释:
      * 用来传递任意个无名字参数,这些参数会一个Tuple的形式访问。

       **用来处理传递任意个有名字的参数,这些参数用dict来访问。*

    应用:
    #########################

    # “*” 的应用

    #########################

    >>> def fun1(*keys):
    ...     print "keys type=%s" % type(keys)
    ...     print "keys=%s" % str(keys)
    ...     for i in range(0, len(keys)):
    ...             print "keys[" + str(i) + "]=%s" % str(keys[i])
    ...
    >>> fun1(2,3,4,5)
    输出以下结果:

    keys type=<type 'tuple'>
    keys=(2, 3, 4, 5)
    keys[0]=2
    keys[1]=3
    keys[2]=4
    keys[3]=5

    #########################

    # “**” 的应用

    #########################

    >>> def fun2(**keys):
    ...     print "keys type=%s" % type(keys)
    ...     print "keys=%s" % str(keys)
    ...     print "name=%s" % str(keys['name'])
    ...
    >>>
    >>> fun2(name="vp", age=19)

    输出以下结果:
    keys type=<type 'dict'>
    keys={'age': 19, 'name': 'vp'}
    name=vp

    再写一个例子

    def test(*arg,**argv):
    print arg
    print argv

    test(1,2,3,4,name='ymy',sex='man')

    输出结果:

  • 相关阅读:
    算法
    算法
    算法
    算法
    mysql使用注意事项
    公共接口限制IP请求次数的一种方式(redis版)
    vue echarts 折线图 饼图 地图
    springboot Redis缓存应用示例
    springboot 响应消息 message简单封装 单例和原型模式
    springboot 请求外部接口方法
  • 原文地址:https://www.cnblogs.com/ymy124/p/4916883.html
Copyright © 2020-2023  润新知