如何修复 Python 中的两个对象同名 'local variable referenced before assignment' 错误
How to fix two object same name 'local variable referenced before assignment' Error in Python
我定义了一个函数,在该函数或另一个函数中,我通过调用同名函数来分配同名值。我收到此错误
UnboundLocalError: local variable 'demo01' referenced before assignment
此处出现错误
def demo01():
return 5
def demo02():
demo01=demo01()
demo02()
UnboundLocalError: local variable 'demo01' referenced before assignment
但这些片段很好
def demo01():
return 5
def demo02():
demo01=demo01()
demo01 = demo01()
def demo01():
return 5
def demo02():
demo02=demo01()
demo02()
当已有变量时,以该名称创建新变量将覆盖现有变量,例如:
print = 2 # change the print() function to a variable named 2
print('string')
会给
TypeError: 'int' object is not callable
回到你的代码:
demo01 = lambda: 5 # this is more of an advanced keyword, feel free to do it your way
def demo02():
demo01 = demo01() # "demo01 = [val]" tells python to assign a value to demo01, and you cannot assign a variable to the same variable:
variable = variable
显然不可能;给出
NameError: name 'variable' is not defined
在全局状态中使用时,在局部状态(class 或函数中使用时出现 UnboundLocalError。
您的变量名称和其他变量(如果有)在赋值期间使用不得是或引用您当前正在赋值的变量。
如果确实需要使用同一个变量:
variable_ = variable()
variable = variable_
我定义了一个函数,在该函数或另一个函数中,我通过调用同名函数来分配同名值。我收到此错误
UnboundLocalError: local variable 'demo01' referenced before assignment
此处出现错误
def demo01():
return 5
def demo02():
demo01=demo01()
demo02()
UnboundLocalError: local variable 'demo01' referenced before assignment
但这些片段很好
def demo01():
return 5
def demo02():
demo01=demo01()
demo01 = demo01()
def demo01():
return 5
def demo02():
demo02=demo01()
demo02()
当已有变量时,以该名称创建新变量将覆盖现有变量,例如:
print = 2 # change the print() function to a variable named 2
print('string')
会给
TypeError: 'int' object is not callable
回到你的代码:
demo01 = lambda: 5 # this is more of an advanced keyword, feel free to do it your way
def demo02():
demo01 = demo01() # "demo01 = [val]" tells python to assign a value to demo01, and you cannot assign a variable to the same variable:
variable = variable
显然不可能;给出
NameError: name 'variable' is not defined
在全局状态中使用时,在局部状态(class 或函数中使用时出现 UnboundLocalError。
您的变量名称和其他变量(如果有)在赋值期间使用不得是或引用您当前正在赋值的变量。
如果确实需要使用同一个变量:
variable_ = variable()
variable = variable_