Python 函数可以记住它之前的输出吗?

Rob*_*tex 5 python function python-3.x

有没有一种方法可以让函数记住其先前的输出并在下次调用该函数时使用该值?例如,假设有一个函数,它runningTotal有一个参数,该参数在第一次调用但之后的每次调用时x返回。有没有办法用python编写这样的函数?xrunningTotalx + prevOutput

我知道通过在函数中使用全局变量或将先前的值保存到新变量可以轻松实现这一点,但如果可能的话,我想避免这些解决方案。我正在寻找替代解决方案的原因是因为这是我正在与其他人一起开发的程序中的一个函数,我希望避免创建比已经建立的更多的全局变量。

Ben*_*ott 3

是的,但为了避免太多黑客行为或全局变量,我们可能需要使用一个类。在 python 中,一个类可以被视为函数,在名为 的类中具有一个神奇的函数(方法)__call__

你的问题可能写得更好:在 python 中拥有具有内部状态的函数的最佳方法是什么?

假设我们使用全局变量定义 runningTotal 函数:

TOTAL = 0
def runningTotal(inc):
    global TOTAL
    TOTAL += inc
    return TOTAL
Run Code Online (Sandbox Code Playgroud)

好的,让我们定义一个类,其行为与上述函数相同,但没有全局变量:


class StatefulFunction:
    running_total = 0

    def __call__(self, inc):
        self.running_total += inc
        return self.running_total


# create the stateful function variable
runningTotal = StatefulFunction()

# Use the stateful function
runningTotal(1)
# outputs: 1
runningTotal(5)
# outputs: 6
Run Code Online (Sandbox Code Playgroud)

完成同样事情的另一种方法是使用计数器字典

from collections import Counter
counter = Counter()
counter['runningTotal'] += 1
# in another part of the program
counter['runningTotal'] += 5
Run Code Online (Sandbox Code Playgroud)

输出将是:

print(counter)
Counter({'runningTotal': 6})
Run Code Online (Sandbox Code Playgroud)