【发布时间】:2017-12-11 21:20:16
【问题描述】:
我相信这是一个简单的问题,但仍想快速明确地回答我的情况:
def get_query_history(idx, url, archive_location):
idx = idx + 1
return idx # I meant to return the idx's value (end up 1000 for every call) and used it in the next loop in main
main:
idx = 1
while current <= end_date:
with open(archive_location, 'a') as the_archive:
get_query_history(idx, url, archive_location) # I want to increase the idx every time I call the function
显然这不是我在 python 中应该采用的方式,有没有人能启发我?
【问题讨论】:
-
你说的是静态变量的概念吗?您可以将
index定义为全局变量,然后只更改全局变量而不重新定义或传递它 -
由于您返回
idx增加的值,只需将其存储回“主”范围:idx = get_query_history(idx, url, archive_location) -
另外,不要为每个
while循环迭代重新使用with open上下文管理器。使用with open...: while... -
最后,您使用
idx作为全局范围内的变量。无需将其传递给函数或从函数返回。循环结束后就可以使用了 -
谢谢@zwer,它有效,我如何选择这个作为答案?感谢所有回复。
标签: python