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

【转载】 Python 方法参数 * 和 **

时间:2015-03-20 18:36:00      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Python的函数定义中有两种特殊的情况,即出现*,**的形式。
如:def myfun1(username, *keys)或def myfun2(username, **keys)等。

他们与函数有关,在函数被调用时和函数声明时有着不同的行为。此处*号不代表C/C++的指针。

其中 * 表示的是元祖或是列表,而 ** 则表示字典

第一种方式:

 1 import httplib
 2 def check_web_server(host,port,path):
 3  h = httplib.HTTPConnection(host,port)
 4  h.request(GET,path)
 5  resp = h.getresponse()
 6  print HTTP Response
 7  print         status =,resp.status
 8  print         reason =,resp.reason
 9  print HTTP Headers:
10  for hdr in resp.getheaders():
11  print         %s : %s % hdr
12  
13  
14 if __name__ == __main__:
15  http_info = {host:www.baidu.com,port:80,path:/}
16  check_web_server(**http_info)

第二种方式:

 1 def check_web_server(**http_info):
 2  args_key = {host,port,path}
 3  args = {}
 4  #此处进行参数的遍历
 5  #在函数声明的时候使用这种方式有个不好的地方就是 不能进行 参数默认值
 6  for key in args_key:
 7  if key in http_info:
 8  args[key] = http_info[key]
 9  else:
10  args[key] = ‘‘
11  
12  
13  h = httplib.HTTPConnection(args[host],args[port])
14  h.request(GET,args[path])
15  resp = h.getresponse()
16  print HTTP Response
17  print         status =,resp.status
18  print         reason =,resp.reason
19  print HTTP Headers:
20  for hdr in resp.getheaders():
21  print         %s : %s % hdr
22  
23  
24 if __name__ == __main__:
25  check_web_server(host= www.baidu.com ,port = 80,path = /)
26  http_info = {host:www.baidu.com,port:80,path:/}
27  check_web_server(**http_info)

 

转载来自:http://my.oschina.net/u/1024349/blog/120298

【转载】 Python 方法参数 * 和 **

标签:

原文地址:http://www.cnblogs.com/dcb3688/p/4354148.html

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