Python函数可以记住其先前的输出吗? [英] Can a Python function remember its previous outputs?

查看:61
本文介绍了Python函数可以记住其先前的输出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以记住函数的先前输出并在下一次调用该函数时使用该值?例如,假设存在一个具有单个参数 x 的函数 runningTotal ,该函数在首次调用 runningTotal x .code>,但之后每次调用 x + prevOutput .有没有办法在python中编写这样的函数?

Is there a way that a function can remember its previous output and use that value during the next call to the function? For instance, assume there is a function, runningTotal with a single argument x that returns x on the first call to runningTotal but x + prevOutput for every call after that. Is there a way to write such a function in python?

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

I am aware that this could be easily achieved by using a global variable in the function or by saving the previous value to a new variable, but I would like to avoid these solutions if possible. The reason I'm looking for an alternate solution is because this is one function in a program I'm working on with other people and I would like to avoid having to create more global variables than already established.

推荐答案

尽管有很多方法可以解决您的问题,但这不是一个好主意.正如@JohnColeman指出的那样,使用闭包在python中模拟静态变量

Although there are ways of doing what you ask, it's not a good idea. As @JohnColeman pointed out, Simulate static variables in python with closures

但是为什么不创建一个类呢?

But why not create a class?

class Accumulator:
    total = 0

    @classmethod
    def add(cls, x):
        cls.total += x
        return cls.total


print(Accumulator.add(1))
print(Accumulator.add(2))
print(Accumulator.add(3))

结果:

1
3
6

您可以按照@HeapOverflow的建议设置生成器以维护状态并向其发送值:

You can set up a generator to maintain state and send values to it as well, as suggested by @HeapOverflow:

def get_running_total():
    def _running_total():
        value = 0
        while True:
            value += yield value
    # get a generator instance
    generator = _running_total()
    # set it up to wait for input
    next(generator)
    # return the send method on the generator
    return generator.send


# you can get a generator that functions similar to the Accumulator method
running_total = get_running_total()
print(running_total(1))   # prints 1
print(running_total(2))   # prints 3
print(running_total(3))   # prints 6

这篇关于Python函数可以记住其先前的输出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆