[英]Python: defining a variable in callback function…not sure where
摘抄:
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
,它仍然會給出一個錯誤的local variable 'sizeWritten referenced before assignment
。 我應該怎么做?
如果sizeWritten
可以是全局的(例如,一次只能有一個回調活動),則可以在函數中將其標記為:
file = open("D:\\DownloadFolder\\test.mp3", "wb")
sizeWritten = 0
def callback(data):
global sizeWritten
file.write(data)
sizeWritten += len(data)
print(sizeWritten)
callback
對該名稱的任何分配都會更改全局名稱。
在Python 3中,您還可以使用閉包和nonlocal
關鍵字:
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
對象封裝在本地名稱空間中。
但是,您可以直接從打開file
file對象獲得相同的信息:
def callback(data):
file.write(data)
print(file.tell())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.