有没有可能在Python中创建一个带有state的嵌套函数?

2024-04-18 12:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试进行一次回调,如果距离上次报告已超过一秒钟,则会进行更新。看起来像这样

def main_func()
    ...
    start_time = time.time()
    def callback():
        current_time = time.time()
        if current_time - start_time > 1.0:
            print 'working'
            start_time = time.time()
    work_function(args, callback)

由于start_time是本地的,global关键字在callback内不起作用。有没有Python范例可以处理向本地函数添加状态的问题?你知道吗


Tags: 距离iftimemaindef报告callbackargs
3条回答

有点,但这是被迫的。你知道吗

    def foo(a):
        def inner(b):
            if b > c[0]:
                c[0] > b
            else:
                print "too low"
        c = [a]
        return inner

>>> bar = foo(5)
>>> bar(5)
too low
>>> bar(6) # silence on success
>>> bar(5)
too low

正如其他人所指出的,最好只使用一个对象(在这个解决方案中,列表毕竟是对象)

如前所述,最好使用类并将状态保存为成员。你知道吗

同样如前所述,您可以使用全局变量或nonlocal语句。你知道吗

第三种(也是更原始的)替代方法是将状态设置为函数对象的属性:

def main_func()
    ...
    def callback():
        current_time = time.time()
        if current_time - callback.start_time > 1.0:
            print 'working'
            callback.start_time = time.time()
    callback.start_time = time.time()
    work_function(args, callback)

您可以做到这一点,但具体细节将取决于您使用的Python版本。你知道吗

在python3中,可以使用nonlocal语句来允许callback函数为外部函数作用域中的start_time变量赋值。你知道吗

def main_func()
    ...
    start_time = time.time()
    def callback():
        nonlocal start_time            # new line here
        current_time = time.time()
        if current_time - start_time > 1.0:
            print 'working'
            start_time = time.time()   # this assignment now works as intended
    work_function(args, callback)

在Python2中,nonlocal不可用,但您可以将值包装在可变容器(如list)中并修改值,而无需重新分配变量:

def main_func()
    ...
    start_time = [time.time()]             # wrap time value in a list
    def callback():
        current_time = time.time()
        if current_time - start_time > 1.0:
            print 'working'
            start_time[0] = time.time()    # modify the list in place
    work_function(args, callback)

相关问题 更多 >