如何修复Python中两个同名的“赋值前引用的局部变量”错误

2024-09-29 23:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个函数,在这个函数或另一个函数中,我通过调用同名函数来分配相同的名称值。我得到这个错误

UnboundLocalError: local variable 'demo01' referenced before assignment

错误发生在这里

def demo01():
    return 5

def demo02():
    demo01=demo01()

demo02()

UnboundLocalError: local variable 'demo01' referenced before assignment

但这些片段很好

^{2}$
def demo01():
    return 5

def demo02():
    demo02=demo01()

demo02()

Tags: 函数名称return定义localdef错误variable
1条回答
网友
1楼 · 发布于 2024-09-29 23:26:49

当存在现有变量时,在该名称下创建新变量将覆盖现有变量,例如:

print = 2 # change the print() function to a variable named 2
print('string')

将给予

^{pr2}$

回到你的代码:

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_

相关问题 更多 >

    热门问题