在接触新浪、腾讯微博开放API的python接口时,我发现了一个很实用但稍显复杂的python特性——可以给一个函数传递灵活的变量,通过传递字典名前面加两个*。比如字典kw= {"username":"testname", "passwd":"123"}传递**kw到函数参数中,通过循环for k, v in kw.iteritems():并利用setattr(self, k, v)给对象进行变量赠加并同时进行赋值。 

如下例子: 

class TEST:
	def __init__(self, url, **kw):
		http_url = url
		for k, v in kw.iteritems():
			setattr(self, k, v)
			http_url = http_url + k + "=" + v + "&"
		http_url = http_url[:-1]
		print http_url

params = {"username":"testname", "passwd":"123"}
test = TEST(url="http://localhost/index.php?", **params)
print test.username
print test.passwd