我定义了一个函数,并在该函数或另一个函数中通过调用同名函数来分配同名值。我收到此错误
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
在全局状态中使用时,在本地(类或函数)中使用时出现 UnboundLocalError。
分配期间使用的变量名称和其他变量(如果有)不得是或引用您当前分配的变量。
如果您确实需要使用相同的变量:
variable_ = variable()
variable = variable_
关于python - 如何修复Python中两个对象同名 'local variable referenced before assignment'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56121439/