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

python args & kwargs

时间:2015-06-26 23:38:57      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

 

Today,We will talk some about the argument and arguments ...

#!/usr/bin/python

def fun(*args):
    for value in args:
        print value


if __name__ == __main__:
    
    fun(11,22,33,44,55)

技术分享

 

What is type of (*args) ?

Do you really want to know ,just keep read ...

#!/usr/bin/python

def fun(*args):
    print type(args)
    for value in args:
        print value


if __name__ == __main__:
    
    fun(11,22,33,44,55)

技术分享

 

Okay,We know the (*args ) just a tuple type?

so,we can input a tuple as argument ...

#!/usr/bin/python

def fun(*args):
    print type(args)
    for value in args:
        print value


if __name__ == __main__:
    
    my_tuple=(11,22,33,44,55)
    fun(my_tuple) 

技术分享

 

Oh,What happened ? The result is no what we expect ...

See the below code,you will find the answer ...

#!/usr/bin/python

def fun(*args):
    print type(args)
    for value in args:
        print value


if __name__ == __main__:
    
    my_tuple=(11,22,33,44,55)
    fun(*my_tuple)

 

技术分享

Okay,see we got the result what we expect ...

 

Good,time to talk (**kwargs)

#!/usr/bin/python

def fun(**kwargs):
    
    print type(kwargs)
    for key in kwargs:
        print key: ,key,value: ,kwargs[key]
    

if __name__ == __main__:
    fun(name=Frank,age=23,school=IMUT)

 

技术分享

 

Of course,you can input a dict as argument,but Don‘t forget the (**) again ...

If you really want to forget (**) ,like the below code ...

#!/usr/bin/python

def fun(**kwargs):
    
    print type(kwargs)
    for key in kwargs:
        print key: ,key,value: ,kwargs[key]
    

if __name__ == __main__:
    my_dict={name:Frank,age:23,school:IMUT}
    fun(my_dict)

 

You will got a error like the below :

技术分享

 

So ,You don‘t really want to do it again ,right ...haha

#!/usr/bin/python

def fun(**kwargs):
    
    print type(kwargs)
    for key in kwargs:
        print key: ,key,value: ,kwargs[key]
    

if __name__ == __main__:
    my_dict={name:Frank,age:23,school:IMUT}
    fun(**my_dict)

 

Okay ! see the right result :

技术分享

 

Thank you !

python args & kwargs

标签:

原文地址:http://www.cnblogs.com/landpack/p/4603378.html

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