python - 赋值前引用的局部变量

标签 python scope

<分区>

我快疯了。这个简单的回调函数无法识别在它的父范围内就在它之前分配的变量。我得到一个 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.

关于python - 赋值前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232869/

相关文章:

python - Django中如何处理数据库异常

python - 插入小时条件

python - 打印无效语法? [Python 3]

javascript - 在外部范围内对变量使用等待内联

java - Java中的变量声明和初始化

python - 预测下一个数字

python - Pip 安装二进制文件并保留requirements.txt

c++ - Vim:使用范围突出显示 C++ 变量?

Javascript 外部对象全局?

c++ - EXTERN 或 STATIC 用于维护许多变量