zoukankan      html  css  js  c++  java
  • Python * args 和 ** kwargs那点事


    1,前言:一般出现*args 和 **kwargs,首先给我想到的是C语言的指针,真的。估计这是用C编写Python没有有阉割干净的缘故。

    2,正题: 什么时候用这两个参数呢,我们通常见得最多的时候是作为函数的参数,当函数的参数不确定时,可以使用*args和 **kwargs,*args 没有key值,**kwargs 有key值。

    3,例子

    def args_test(param1,*args):
        print "first param is:",param1
        index = 1
        for value in args:
           print "the "+str(index)+" is:"+str(value)
           index += 1
    
    def kwargs_test(param1,**kwargs):
        print "the first param is: ",param1
        for key in kwargs:
            print "the key is: %s, and the value is: %s" %(key,kwargs[key])
    
    if __name__ == "__main__":
        args_test('ha',1,'a','b','d','test')
        kwargs_test('hi,kwargs',tom = 30,lilei = 28,hamei = 29)
    

    程序结果:

    first param is: ha
    the 1 is:1
    the 2 is:a
    the 3 is:b
    the 4 is:d
    the 5 is:test
    the first param is:  hi,kwargs
    the key is: lilei, and the value is: 28
    the key is: hamei, and the value is: 29
    the key is: tom, and the value is: 30 
    

    4,总结:*args可以传入列表,元组。**kwargs可以传入字典作为参数。

  • 相关阅读:
    当前网页调用其他网页
    保护自己的网页不被放入框架
    保护网页源码
    页面的后退、刷新、前进
    妙味——拖拽+碰撞+重力
    运行代码
    妙味——弹性运动
    IE css bug及解决方案参考
    妙味——布局转换的应用
    [LeetCode][JavaScript]Count Complete Tree Nodes
  • 原文地址:https://www.cnblogs.com/codeblock/p/python_args_kwargs.html
Copyright © 2011-2022 走看看