*args and **kwargs in Python 变长参数

原文链接

变长参数
  • args(非关键字参数)
def myFun(*argv): 
    for arg in argv: 
        print (arg)
   
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') 
Hello
Welcome
to
GeeksforGeeks
# Python program to illustrate 
# *args with first extra argument
def myFun(arg1, *argv):
    print ("First argument :", arg1)
    for arg in argv:
        print("Next argument through *argv :", arg)
 
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks
  • ** kwargs(关键字参数)
def myFun(**kwargs): 
    
    # print(kwargs)
    for key, value in kwargs.items():
        print ("%s == %s" %(key, value))
    print('#'*12)
 
# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')    

input_dict={'first' :'Geeks', 'mid' :'for', 'last':'Geeks'}
myFun(**input_dict)
first == Geeks
mid == for
last == Geeks
############
first == Geeks
mid == for
last == Geeks
############
def myFun(arg1, **kwargs): 
    for key, value in kwargs.items():
        print ("%s == %s" %(key, value))
 
# Driver code
myFun("Hi", first ='Geeks', mid ='for', last='Geeks')  
first == Geeks
mid == for
last == Geeks
这种用法感觉非常奇怪
def myFun(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)
     
# Now we can use *args or **kwargs to
# pass arguments to this function : 
args = ("Geeks", "for", "Geeks")
myFun(*args)
 
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"}
myFun(**kwargs)

posted @ 2022-08-19 22:50  luoganttcc  阅读(8)  评论(0)    收藏  举报