【问题标题】:passing parameter and retain value after function call in python在python中的函数调用后传递参数并保留值
【发布时间】: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


【解决方案1】:

在这里,我将其作为答案发布,但我会扩大一点。

由于您返回 idx 增加的值,只需将其存储回“主”范围:

idx = 1 
while current <= end_date:
    with open(archive_location, 'a') as the_archive:
        idx = get_query_history(idx, url, archive_location)
    # make sure you update your `current` ;)

在某些语言中,您可以选择通过引用将变量传递给函数,这样函数可以更改其值,因此您无需返回值。 Python 是通过引用传递的,但由于简单值是不可变的,只要您尝试在函数中设置其值,对传递值的 reference 就会被覆盖。

这不适用于封装对象,因此您可以将 idx 封装在一个列表中,然后将其作为列表传递。在这种情况下,您根本不需要 return:

def get_query_history(idx, url, archive_location):
    idx[0] += 1
    # do whatever else

# in your main:

idx = [1]  # encapsulate the value in a list
while current <= end_date:
    with open(archive_location, 'a') as the_archive:
        get_query_history(idx, url, archive_location)  # notice, no return capture
    # make sure you update your `current` ;)

但一般来说,如果可以返回值就不需要这些恶作剧了,这只是为了证明一个函数可以在某些条件下修改传递的参数。

最后,如果你真的想强制传递引用行为,你可以完全破解 Python 来做到这一点,check this(并且永远不要在生产中使用它!);)

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 1970-01-01
    • 2022-12-11
    • 2013-01-05
    • 2013-11-06
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多