406
技術社區[雲棲]
Python 中方法參數 * 和 ** 的例子
在Python中* 和 ** 有特殊含義,他們與函數有關,在函數被調用時和函數聲明時有著不同的行為。此處*號不代表C/C++的指針。
其中 * 表示的是元祖或是列表,而 ** 則表示字典
以下為 ** 的例子:
01
|
#--------------------第一種方式----------------------#
|
03
|
def check_web_server(host,port,path):
|
04
|
h = httplib.HTTPConnection(host,port)
|
06
|
resp = h.getresponse()
|
08
|
print '
status =',resp.status
|
09
|
print '
reason =',resp.reason
|
11
|
for hdr in resp.getheaders():
|
12
|
print '
%s : %s' % hdr
|
15
|
if __name__ == '__main__':
|
16
|
http_info = {'host':'www.baidu.com','port':'80','path':'/'}
|
17
|
check_web_server(**http_info)
|
另一種方式:
01
|
#--------------------第二種方式----------------------#
|
04
|
def check_web_server(**http_info):
|
05
|
args_key = {'host','port','path'}
|
08
|
#在函數聲明的時候使用這種方式有個不好的地方就是
不能進行 參數默認值
|
11
|
args[key] = http_info[key]
|
16
|
h = httplib.HTTPConnection(args['host'],args['port'])
|
17
|
h.request('GET',args['path'])
|
18
|
resp = h.getresponse()
|
20
|
print '
status =',resp.status
|
21
|
print '
reason =',resp.reason
|
23
|
for hdr in resp.getheaders():
|
24
|
print '
%s : %s' % hdr
|
27
|
if __name__ == '__main__':
|
28
|
check_web_server(host= 'www.baidu.com' ,port = '80',path = '/')
|
29
|
http_info = {'host':'www.baidu.com','port':'80','path':'/'}
|
30
|
check_web_server(**http_info)
|
最後更新:2017-04-03 21:13:16