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 !
原文:http://www.cnblogs.com/landpack/p/4603378.html