我快疯了。这个简单的回调函数无法识别在它的父范围内就在它之前分配的变量。我得到一个 local variable 'elapsed' referenced before assignment
错误`。为什么?
total = os.path.getsize(filename)
elapsed = 0
def progress_print(chunk):
elapsed += len(chunk) # elapsed is apparently unassigned??
percent = float(elapsed) / float(total) * 100
print ' Copied %s%%\033[A' % int(percent)
ftp.upload(filename, temp_path, callback=progress_print)
您正在尝试分配给全局。 Python 让您明确地这样做。
def progress_print(chunk):
global elapsed
elapsed += len(chunk)
一般来说,这是一个很好的迹象,表明您需要重构代码,直到您不再需要全局变量。
请注意,分配和访问是不同的野兽 - 前者要求您显式声明全局变量,后者则不需要。例如,您的 total
变量是另一个全局变量,但您没有尝试分配给它,因此 python 不会提示。
Programming FAQ进入更多细节:
What are the rules for local and global variables in Python?
In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a new value anywhere
within the function’s body, it’s assumed to be a local. If a variable
is ever assigned a new value inside the function, the variable is
implicitly local, and you need to explicitly declare it as ‘global’.
Though a bit surprising at first, a moment’s consideration explains
this. On one hand, requiring global for assigned variables provides a
bar against unintended side-effects. On the other hand, if global was
required for all global references, you’d be using global all the
time. You’d have to declare as global every reference to a built-in
function or to a component of an imported module. This clutter would
defeat the usefulness of the global declaration for identifying
side-effects.