Python:在回调函数中定义变量...不确定在哪里 [英] Python: defining a variable in callback function...not sure where

查看:70
本文介绍了Python:在回调函数中定义变量...不确定在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

节选:

file = open("D:\\DownloadFolder\\test.mp3", "wb")

def callback(data):
    file.write(data)
    sizeWritten += len(data)
    print(sizeWritten)

connect.retrbinary('RETR test.mp3', callback)
print("completed")

Python显然抱怨我没有定义 sizeWritten ,但是我不确定应该在哪里定义它.如果将 sizeWritten = 0 放在函数之前,它仍会给出错误局部变量'sizeWritten在赋值之前引用.我该怎么办?

Python obviously complains that I didn't define sizeWritten, but I'm not sure where I should define it. If I put sizeWritten = 0 before the function it still gives an error local variable 'sizeWritten referenced before assignment. How should I do this?

推荐答案

如果 sizeWritten 可以是全局的(例如,永远只有一个 一次启用回调),您可以在函数中将其标记为:

If it is okay for sizeWritten to be a global (e.g. there is only ever going to be one callback active at a time), you can mark it as such in your function:

file = open("D:\\DownloadFolder\\test.mp3", "wb")
sizeWritten = 0

def callback(data):
    global sizeWritten
    file.write(data)
    sizeWritten += len(data)
    print(sizeWritten)

callback 中对该名称的任何分配都会更改全局.

and any assignments to the name in callback alter the global.

在Python 3中,您还可以使用闭包和 nonlocal 关键字:

In Python 3, you can also use a closure, and the nonlocal keyword:

def download(remote, local):
    file = open(local, "wb")
    sizeWritten = 0

    def callback(data):
        nonlocal sizeWritten
        file.write(data)
        sizeWritten += len(data)
        print(sizeWritten)

    connect.retrbinary('RETR ' + remote, callback)
    print("completed")

这至少将 sizeWritten file 对象封装在本地名称空间中.

This encapsulates the sizeWritten and file objects in a local namespace, at least.

但是,您可以直接从打开的 file 文件对象中获得相同的信息:

However, you could get the same information directly from the open file file object:

def callback(data):
    file.write(data)
    print(file.tell())

这篇关于Python:在回调函数中定义变量...不确定在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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