美文网首页
[python 百日笔记]第13课-函数的参数

[python 百日笔记]第13课-函数的参数

作者: Silver_42ac | 来源:发表于2019-11-24 13:15 被阅读0次

    1、第一种形式

    #l 为一个预置的列表变量,但是在参数里,也就表示可以作为参数导入
    def f(a, l=[]):
        l.append(a)
        return l
        
    # 此时调用函数
    print(f(1))
    print(f(2))
    print(f(3))
    
    # 返回值
    # [1]
    # [1, 2]
    # [1, 2, 3]
    

    2、可变参数

    其中
    *args代表一个list或者tuple
    **args代表着可以传入一个dict

    def variable_fun(kind, *arguments, **keywords):
        print("friend : ", kind, ";")
        print("-" * 40)
        for arg in arguments:
            print(arg)
        print("-" * 40)
        for kw in keywords:
            print(kw, ":", keywords[kw])
            
    #这里我调整了例子,只是用最方便理解的做笔记
    kind="test"
    tuple_var=("aa","bb","vvv","ddd")
    list_var=["aa","bb","vvv","ddd"]
    dict_var={"aa":1 , "bb":2 , "vvv":3 , "ddd":4}
    #variable_fun(kind,*tuple_var,*dict_var)
    variable_fun(kind,*list_var,*dict_var)
    

    例子在这里:可以运行,也可以自己修改
    https://glot.io/snippets/fi50i2z87u
    https://glot.io/ 这个网站可以自己选择语言网站上测试

    输出内容如下:

    friend :  test ;
    ----------------------------------------
    aa
    bb
    vvv
    ddd
    ----------------------------------------
    aa : 1
    bb : 2
    vvv : 3
    ddd : 4
    

    参考:
    https://mp.weixin.qq.com/s/EA6UAU5zOzK6pd5GYzK1Wg

    不方便理解的

    variable_fun("test","aa","bb","vvv","ddd","aa"=1 , "bb"=2 , "vvv"=3 , "ddd"=4)
    #variable_fun(kind, *arguments, **keywords)
    #python 会根据变量性质自动把"test" 给kind;可以匹配为 list 或者 tuple 的"aa","bb","vvv","ddd"  作为arguments 变量
    
    #字典形式的"aa"=1 , "bb"=2 , "vvv"=3 , "ddd"=4识别为 keywords
    

    相关文章

      网友评论

          本文标题:[python 百日笔记]第13课-函数的参数

          本文链接:https://www.haomeiwen.com/subject/vwllwctx.html