Python 中方法参数 * 和 ** 的例子

    在Python中* 和 ** 有特殊含义,他们与函数有关,在函数被调用时和函数声明时有着不一样的行为。此处*号不表明C/C++的指针。 python

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

如下为 ** 的例子: 函数

#--------------------第一种方式----------------------#
import httplib
def check_web_server(host,port,path):
 h = httplib.HTTPConnection(host,port)
 h.request('GET',path)
 resp = h.getresponse()
 print 'HTTP Response'
 print '		status =',resp.status
 print '		reason =',resp.reason
 print 'HTTP Headers:'
 for hdr in resp.getheaders():
 print '		%s : %s' % hdr


if __name__ == '__main__':
 http_info = {'host':'www.baidu.com','port':'80','path':'/'}
 check_web_server(**http_info)
另外一种方式:
#--------------------第二种方式----------------------#


def check_web_server(**http_info):
 args_key = {'host','port','path'}
 args = {}
 #此处进行参数的遍历
 #在函数声明的时候使用这种方式有个很差的地方就是 不能进行 参数默认值
 for key in args_key:
 if key in http_info:
 args[key] = http_info[key]
 else:
 args[key] = ''


 h = httplib.HTTPConnection(args['host'],args['port'])
 h.request('GET',args['path'])
 resp = h.getresponse()
 print 'HTTP Response'
 print '		status =',resp.status
 print '		reason =',resp.reason
 print 'HTTP Headers:'
 for hdr in resp.getheaders():
 print '		%s : %s' % hdr


if __name__ == '__main__':
 check_web_server(host= 'www.baidu.com' ,port = '80',path = '/')
 http_info = {'host':'www.baidu.com','port':'80','path':'/'}
 check_web_server(**http_info)
相关文章
相关标签/搜索