分享循环内的回调函数,问题出现在循环体内的回调函数,用一个很简单的例子举例: 1. <p><font size="3"> print "requests begin:%s"%x</font></p> 2. <p><font size="3"> def callback(respon):</font></p> 3. <p><font size="3"> print x</font></p> 4. <p><font size="3"> print respon.body</font></p> 5. <p><font size="3"> client.fetch("http:///get?x=%s" % x, callback)</font></p>
1. <p><font size="3"> "args": {</font></p> 2. <p><font size="3"> "x": "0"</font></p> 3. <p><font size="3"> },</font></p> 4. <p><font size="3"> "headers": {</font></p> 5. <p><font size="3"> "Accept-Encoding": "gzip",</font></p> 6. <p><font size="3"> "Connection": "close",</font></p> 7. <p><font size="3"> "Host": "",</font></p> 8. <p><font size="3"> "X-Request-Id": "95df3c15-7ed0-4a6d-830d-fb9629e66515"</font></p> 9. <p><font size="3"> },</font></p> 10. <p><font size="3"> "origin": "192.81.129.91",</font></p> 11. <p><font size="3"> "url": "http:///get?x=0"</font></p> 12. <p><font size="3"> }</font></p>
1. <p><font size="3"> for x in xrange(3):</font></p> 2. <p><font size="3"> def callback(respon,num=x):</font></p> 3. <p><font size="3"> print x, num</font></p> 4. <p><font size="3"> print respon.body</font></p> 5. <p><font size="3"> if num == 2:</font></p> 6. <p><font size="3"> self.stop()</font></p> 7. <p><font size="3"> client.fetch("http:///get?x=%s" % x, wrap(x))</font></p>
1. <p><font size="3"> for x in xrange(3):</font></p> 2. <p><font size="3"> def wrap(number):</font></p> 3. <p><font size="3"> num = number</font></p> 4. <p><font size="3"> def callback(respon):</font></p> 5. <p><font size="3"> print x, num</font></p> 6. <p><font size="3"> print respon.body</font></p> 7. <p><font size="3"> if num == 2:</font></p> 8. <p><font size="3"> self.stop()</font></p> 9. <p><font size="3"> return callback</font></p> 10. <p><font size="3"> client.fetch("http:///get?x=%s" % x, wrap(x))</font></p> 11. <p><font size="3"> #wrap放在for外面:</font></p> 12. <p><font size="3"> client = AsyncHTTPClient(self.io_loop)</font></p> 13. <p><font size="3"> def wrap(number):</font></p> 14. <p><font size="3"> num = number</font></p> 15. <p><font size="3"> def callback(respon):</font></p> 16. <p><font size="3"> print x, num</font></p> 17. <p><font size="3"> print respon.body</font></p> 18. <p><font size="3"> if num == 2:</font></p> 19. <p><font size="3"> self.stop()</font></p> 20. <p><font size="3"> return callback</font></p> 21. <p><font size="3"> for x in xrange(3):</font></p> 22. <p><font size="3"> client.fetch("http:///get?x=%s" % x, wrap(x))</font></p>
|
|
来自: 昵称63557054 > 《文件夹1》