Skip to main content
 首页 » 编程设计

python之这个 "referenced before assignment"怎么样

2025年05月04日10mate10pro

我会一点 Python 来连接到数据库,并在本地和实时之间切换。

    LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"} 
    LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"} 
 
    if debug_mode: 
        connection_info = LOCAL_CONNECTION 
    else: 
        connnection_info = LIVE_CONNECTION 
    self.connection = MySQLdb.connect(host = connection_info["server"], user = connection_info["user"], passwd = connection_info["password"], db = connection_info["database"]) 

在本地(Windows、Python 2.5)工作正常但在实时(Linux、Python 2.4)我得到:

UnboundLocalError: local variable 'connection_info' referenced before assignment 

即使我删除 if/else 并将连接信息直接分配给 LIVE_CONNECTION 值,我也会看到同样的错误。如果我将实时连接值硬编码到最后一行,一切正常。显然我困了。我没看到什么?

请您参考如下方法:

第二个作业拼写错误。

您用 3 个 n 编写了 connnection_info = LIVE_CONNECTION。