- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对局部变量和 python (2.7) 有一些小问题。
我有一些代码:
def foo(a):
def bar():
print a
return bar()
>>>foo(5)
5
好吧,它可以工作,但是如果想修改 a ,像这样:
def foo(a):
def bar():
a -= 1
return bar()
>>>foo(5)
UnboundLocalError: local variable 'a' referenced before assignment
所以我必须将“a”影响到另一个变量。
但是我不明白这种行为。是因为当有赋值时,python 在 locals() 变量中查找并没有找到它吗?
谢谢。
最佳答案
您发现了一些曾经在 Python 中存在的问题!简短的回答是,您不能在 Python 2.x 中执行此操作(尽管您可以 simulate ),但您可以在 3.x 中使用 nonlocal
关键字。
参见 PEP 3104 :
Before version 2.1, Python's treatment of scopes resembled that of standard C: within a file there were only two levels of scope, global and local. In C, this is a natural consequence of the fact that function definitions cannot be nested. But in Python, though functions are usually defined at the top level, a function definition can be executed anywhere. This gave Python the syntactic appearance of nested scoping without the semantics, and yielded inconsistencies that were surprising to some programmers -- for example, a recursive function that worked at the top level would cease to work when moved inside another function, because the recursive function's own name would no longer be visible in its body's scope. This violates the intuition that a function should behave consistently when placed in different contexts. Here's an example:
def enclosing_function():
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1) # fails with NameError
print factorial(5)Python 2.1 moved closer to static nested scoping by making visible the names bound in all enclosing scopes (see PEP 227). This change makes the above code example work as expected. However, because any assignment to a name implicitly declares that name to be local, it is impossible to rebind a name in an outer scope (except when a global declaration forces the name to be global). Thus, the following code, intended to display a number that can be incremented and decremented by clicking buttons, doesn't work as someone familiar with lexical scoping might expect:
def make_scoreboard(frame, score=0):
label = Label(frame)
label.pack()
for i in [-10, -1, 1, 10]:
def increment(step=i):
score = score + step # fails with UnboundLocalError
label['text'] = score
button = Button(frame, text='%+d' % i, command=increment)
button.pack()
return labelPython syntax doesn't provide a way to indicate that the name score mentioned in increment refers to the variable score bound in make_scoreboard, not a local variable in increment. Users and developers of Python have expressed an interest in removing this limitation so that Python can have the full flexibility of the Algol-style scoping model that is now standard in many programming languages, including JavaScript, Perl, Ruby, Scheme, Smalltalk, C with GNU extensions, and C# 2.0.
关于python 和 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9720626/
以下代码在 Python 2.5 和 3.0 中都按预期工作: a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) prin
以下代码在 Python 2.5 和 3.0 中都按预期工作: a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) prin
从 string 导入时模块,与解析函数一起使用。 from string import punctuation def parsing_func(data): if not any(i==v
mt=0 ft=0 def amount_total(g): if g=="male": mt=mt+amount else: ft=ft+amount
我正在尝试在 leetcode 中解决这个问题。我是 leetcode 的新手。我收到 UnboundLocalError: local variable 'i' referenced before
这个问题已经有答案了: UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned
也许我今天早上的咖啡不够浓,但这种行为现在让我感到困惑: >>> a = 'foo' >>> def func1(): ... print a ... >>> def func2(): ...
我是编程新手,但我喜欢自然语言(如您所见)。我正在尝试编写一个简单的程序来帮助测试法语现在时动词。但是,在这段代码中,我不断收到错误消息,因为 CorrectAnswers 显然尚未设置为全局变量。有
def create_school(school,year): all_students = {} achievements= {} var = data.Files.get(
我正在使用 django 1.8 和 python 2.7,但我不断收到 unbounLocalError。我的views.py 中的代码看起来一切正常。但它保留分配之前引用的局部变量“cd”。如果有
例如: $ cat -n foo.py 1 def f(): 2 str = len 3 str = str('abc') 4 #
def main(): cash = float(input("How much money: ")) coins = 0 def changeCounter(n): whil
我对局部变量和 python (2.7) 有一些小问题。 我有一些代码: def foo(a): def bar(): print a return bar() >>>
这个问题在这里已经有了答案: Using global variables in a function (25 个答案) 关闭 4 年前。 所以,我一直在使用 python 作为命令提示符应用程序开
我刚开始编程并尝试写一些东西但(当然)它失败了。在我找到真正的问题之后:UnboundLocalError。因此,为了让您远离周围的所有废墟,我将代码简化为: def test(): try:
我继承了一个遗留单元测试,它试图覆盖嵌套在另一个类中的自定义类的名称 datetime。我现在正在重构它(我同意这很糟糕)但我不明白我看到的特定错误。 我看到了一个UnboundLocalError,
这个问题在这里已经有了答案: UnboundLocalError trying to use a variable (supposed to be global) that is (re)assig
这个问题在这里已经有了答案: UnboundLocalError on nested module reimport [duplicate] (2 个答案) 关闭 4 年前。 我被 python 解
这个问题在这里已经有了答案: Is it possible to modify a variable in python that is in an outer (enclosing), but n
我在 View 中有一个函数,用于上传 CSV 数据并写入数据库。那部分正在工作。但是,当我尝试检查是否有数据更新或创建时,我收到一条错误消息: "local variable 'created' r
我是一名优秀的程序员,十分优秀!