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

时间:2023-01-01 22:24:37

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

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

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

第一种方式:

 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':'','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 = '',path = '/')
http_info = {'host':'www.baidu.com','port':'','path':'/'}
check_web_server(**http_info)

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