gpt4 book ai didi

python - 令人困惑的范围变化 - 发生了什么事?

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:55 25 4
gpt4 key购买 nike

def Test(value):
def innerFunc():
print value
innerFunc()

def TestWithAssignment(value):
def innerFunc():
print value
value = "Changed value"
innerFunc()

Test("Hello 1")
# Prints "Hello 1"

TestWithAssignment("Hello 2")
# Throws UnboundLocalError: local variable 'value' referenced before assignment
# on the "print value" line

为什么第二个失败,因为唯一的区别是在打印语句之后的赋值?我对此很困惑。

最佳答案

问题在于 Python 希望您是显式的,而您希望是隐式的。 execution model Python 使用将名称绑定(bind)到最近的可用 封闭 范围。

def Test(value):
# Local Scope #1
def innerFunc():
# Local Scope #2
print value
# No immediate local in Local Scope #2 - check up the chain
# First find value in outer function scope (Local Scope #1).
# Use that.
innerFunc()

def TestWithAssignment(value):
# Local Scope #1
def innerFunc():
# Local Scope #2
print value
# Immediate local variable found in Local Scope #2.
# No need to check up the chain.
# However, no value has been assigned to this variable yet.
# Throw an error.
value = "Changed value"
innerFunc()

(据我所知)没有一种方法可以在 Python 2.x 中遍历范围 - 你有 globals()locals() -但是全局和本地范围之间的任何范围都无法访问(如果这不是真的,我希望得到纠正)。

但是,您可以将局部变量 value 传递到您的内部局部作用域中:

def TestWithAssignment(value):
def innerFunc(value):
print value
# Immediate local **and assigned now**.
value = "Changed value"
# If you need to keep the changed value
# return value
innerFunc(value)
# If you need to keep the changed value use:
# value = innerFunc(value)

在 Python 3 中你有新的 nonlocal可用于引用包含范围的语句(感谢@Thomas K)。

def TestWithAssignment(value):
def innerFunc():
nonlocal value
print value
value = "Changed value"
innerFunc()

关于python - 令人困惑的范围变化 - 发生了什么事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6832836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com