【Python基础】*args,**args的详细用法

 Python基础知识:*args,**args的详细用法

参考:https://blog.csdn.net/qq_29287973/article/details/78040291

*args 不定参数,**kwargs 传入键值对(例如:num1=11,num2=22)

先看示例1:

def test(a,b,c=3,*args):
    print(a)
    print(b)
    print(c)
    print(args)
test(11,22,33,44,55)
1 11
2 22
3 33
4 (44,55)
输出结果

也就是说args中保存的是没有利用的所有多余参数,保存方式为元组

再看示例2:

def test(a,b,c=3,*args1,**args2):  
    print(a)  
    print(b)  
    print(c)  
    print(args1)
    print(args2)  
test(11,22,33,dd=44,ee=55,ff=66)  
1 11
2 22
3 33
4 ()
5 {'dd':44, 'ee':55, 'ff':66}
输出结果

即输入多余参数有变量名,就保存在**args中保存,保存方式为字典

再看示例3:

def test(a,b,c=3,*args1,**args2):
    print(a)
    print(b)
    print(c)
    print(args1)
    print(args2)

test(11,22,33,"aa","bb",dd=44,ee=55,ff=66)
1 11
2 22
3 33
4 ('aa', 'bb')
5 {'dd': 44, 'ee': 55, 'ff': 66}
输出结果

 

 

补充:

import requests
 
response = requests.get('http://httpbin.org/get')
print(response.text)
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "223.71.166.246", 
  "url": "http://httpbin.org/get"
}
输出结果

带参数的get请求,方式1:

import requests
 
response = requests.get('http://httpbin.org/get?name=xiong&age=25')
print(response.text)
{
  "args": {
    "age": "25", 
    "name": "xiong"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "223.71.166.246", 
  "url": "http://httpbin.org/get?name=0bug&age=25"
}
输出结果

带参数的get请求,方式2:

params 表示函数的参数是可变个数的

import requests
 
data = {
    'name': 'xiong',
    'age': 25
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.text)
{
  "args": {
    "age": "25", 
    "name": "xiong"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "223.71.166.246", 
  "url": "http://httpbin.org/get?name=0bug&age=25"
}
输出结果
posted @ 2019-01-23 14:29  XJT2019  阅读(5530)  评论(0编辑  收藏  举报