如何利用python闭包编写回调函数 [英] how to leverage python closure to write callback functions

查看:62
本文介绍了如何利用python闭包编写回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在亚马逊的手册页上找到了此代码.它用作创建回调对象,可以将其作为

i've found this code on the man page of amazon. It is used as a to create callback objects that can be passed as argument of the upload function of the transfer module:

class ProgressPercentage(object):

def __init__(self, filename):
    self._filename = filename
    self._size = float(os.path.getsize(filename))
    self._seen_so_far = 0
    self._lock = threading.Lock()

def __call__(self, bytes_amount):
    # To simplify we'll assume this is hooked up
    # to a single filename.
    with self._lock:
        self._seen_so_far += bytes_amount
        percentage = (self._seen_so_far / self._size) * 100
        sys.stdout.write(
            "\r%s  %s / %s  (%.2f%%)" % (
                self._filename, self._seen_so_far, self._size,
                percentage))
        sys.stdout.flush()

使用一个类来保留后续调用所需的状态(即self.seen_so_far)

a class is used to retain the state necessary for the subsequent calls (self.seen_so_far i.e.)

是否有一种方法可以重新实现为利用python闭包以确保有状态性的功能?

is there a way to reimplement this as a function taking advantage of python closure to ensure statefulness ?

推荐答案

当然,简单的音译应该是这样的:

Sure, a straightforward transliteration would be something like:

def ProgressPrecentage(filename):
    size = os.path.getsize(filename)
    seen_so_far = 0
    lock = threading.Lock()
    def worker(bytes_amount):
        nonlocal seen_so_far
        with lock:
            seen_so_far += bytes_amount
            percentage = (seen_so_far / size)*100
            msg = "\r%s  %s / %s  (%.2f%%)" % (
                filename, seen_so_far, size, percentage
            )
            sys.stdout.write(msg)
            sys.stdout.flush()
    return worker

这篇关于如何利用python闭包编写回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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