• Python中*args和**kargs如何使用


    对于初学者来说,看到*args和**kargs就头大,到底它们有何用处,怎么使用?本文将和大家一起来扒一扒,希望对大家学习python有所帮助。

    1.*args 实质就是将函数传入的参数,存储在元组类型的变量args当中

    def fun_var_args(farg, *args):
    
        print "farg:", farg
    
        for value in args:
    
            print "other arg:", value
    
    fun_var_args(1, "two")
    

    运行:

    farg: 1
    other arg: two

    def fun_var_args(farg, *args):
    
        print "farg:", farg
    
        for value in args:
    
            print "other arg:", value
    
    fun_var_args(1, "two",3,4,5)
    

    运行:

    farg: 1
    other arg: two
    other arg: 3
    other arg: 4
    other arg: 5

    2.第二种场景:

    def fun_input_list(var1,var2,var3):
        print var1,var2,var3
    
    var_list=["second",3]
    fun_input_list(1,*var_list)
    

    运行:

    1 second 3

    def fun_input_list(var1,var2,var3):
        print var1,var2,var3
    
    var_list=["second",3,4,5]
    fun_input_list(1,*var_list)
    

    运行:(注意:运行有错误,故意的)  

    fun_input_list(1,*var_list)
    TypeError: fun_input_list() takes exactly 3 arguments (5 given)

    threading中使用*args

    1.两个传参

    # encoding: utf-8
    from time import ctime,sleep
    import threading
    
    # 定义自己类的功能
    class MyThread(threading.Thread):
        def __init__(self, func, args):
            threading.Thread.__init__(self)
            self.func = func
            self.args = args
        # 调用start自动执行的函数
        def run(self):
            self.func(*self.args)
    def player(song_file,time):
        for i in range(2):
            print("start player %s . %s"%(song_file,ctime()) )
        sleep(time)
    
    threads = []
    
    t = MyThread(player,('You and me .mp3',7))
    
    threads.append(t)
    t.start()
    t.join()
    

    运行:

    start player You and me .mp3 . Wed Jul 18 23:40:30 2018
    start player You and me .mp3 . Wed Jul 18 23:40:30 2018

    1.一个传参,注意args的传值('You and me .mp3',),这里是元祖类型。

    # encoding: utf-8
    from time import ctime,sleep
    import threading
    
    # 定义自己类的功能
    class MyThread(threading.Thread):
        def __init__(self, func, args):
            threading.Thread.__init__(self)
            self.func = func
            self.args = args
        # 调用start自动执行的函数
        def run(self):
            self.func(*self.args)
    def player(song_file):
        for i in range(2):
            print("start player %s ."%(song_file) )
    
    threads = []
    t = MyThread(player,('You and me .mp3',))
    threads.append(t)
    t.start()
    t.join()
    

    运行:

    start player You and me .mp3 .
    start player You and me .mp3 .

    一个或者多个传参

    # encoding: utf-8
    from time import ctime,sleep
    import threading
    
    # 定义自己类的功能
    class MyThread1(threading.Thread):
    
        def __init__(self, func, args):
            threading.Thread.__init__(self)
            self.func = func
            self.args = args
    
        def run(self):
            self.func(*self.args)
    
    class MyThread2(threading.Thread):
    
        def __init__(self, func):
            threading.Thread.__init__(self)
            self.func = func
    
        def run(self):
            self.func()
    
    def player1():
        for i in range(2):
            print"start player."
    
    def player2(song_file):
        for i in range(2):
            print("start player %s ."%(song_file) )
    
    args = 'You and me .mp3'
    threads = []
    t1 = MyThread2(player1)
    threads.append(t1)
    t2 = MyThread1(player2,(args,))
    threads.append(t2)
    print threads
    for t in threads:
        t.setDaemon(True)
        t.start()
    for t in threads:
        t.join()
    

    运行:

    [<MyThread2(Thread-1, initial)>, <MyThread1(Thread-2, initial)>]
    start player.
    start player.
    start player You and me .mp3 .
    start player You and me .mp3 .

    3.**kargs 实质就是将函数的参数和值,存储在字典类型的kargs变量中

    def fun_var_kargs(farg,**kargs):
        print "firsr value %s"% farg
        for key in kargs.keys():
            print key,
            print kargs[key],
    
    fun_var_kargs(1,var1="second",var2=35,var3="third")
    

    运行:注意字典是二分法读取的,所以先var1="second",然后var3="third",最后var2=35

    firsr value 1
    var1 second var3 third var2 35

    注:print key + ":" + kargs[key],这个为什么不能用

    def fun_var_kargs(farg,**kargs):
        print "firsr value %s"% farg
        for key in kargs.keys():
            print key + ":" + kargs[key],
    
    fun_var_kargs(1,var1="second",var2=35,var3="third")
    

    运行:

    print key + ":" + kargs[key],
    TypeError: cannot concatenate 'str' and 'int' objects
    firsr value 1
    var1:second var3:third

    4.**kargs的第二种使用场景

    def fun_input_dic(var1,var2,var3):
        print var1,var2,var3
    
    dic_input={"var2":2,"var3":"third"}
    fun_input_dic(1,**dic_input)
    

    运行:

    1 2 third

    注意*dic_input的运行结果,那就跟*dic_input用法一样了。

    def fun_input_dic(var1,var2,var3):
        print var1,var2,var3
    
    dic_input={"var2":2,"var3":"third"}
    fun_input_dic(1,*dic_input)
    

    运行:

    1 var3 var2

  • 相关阅读:
    (转)C3P0连接池配置和实现详解
    (转)jquery插件Validate的使用
    二叉树和翻转二叉树
    利用@media screen实现网页布局的自适应
    (转)防止SQL注入的五种方法
    java代码规范
    Java泛型-类型擦除
    js中的isNaN()
    (转)sublime 一些常用功能和快捷键
    (转)java中不常见的关键字:strictfp,transient
  • 原文地址:https://www.cnblogs.com/anita-harbour/p/9333586.html
Copyright © 2020-2023  润新知