构造函数不识别属性成员

时间:2013-02-25 21:14:03

标签: python

我的Dbconn类有以下构造函数:

def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except:
        print "There was an error while connecting to the database"
        self.db.rollback()

然而,当我执行程序时,我得到:

  File "database.py", line 39, in __init__
    self.db.rollback()
AttributeError: Dbconn instance has no attribute 'db'

为什么我得到了这个?

3 个答案:

答案 0 :(得分:4)

MySQLdb.connect()失败时,self.db未设置 。在这一点上回滚是没有意义的。

首先将其设置为None,然后在except处理程序中对其进行测试:

db = None

def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except MySQLdb.Error:
        print "There was an error while connecting to the database"
        if self.db is not None:
            self.db.rollback()

我还使异常处理程序更具体;毯子except处理程序很少是个好主意。

答案 1 :(得分:1)

如果self.db抛出异常,则不会将MySQLdb.connect分配给任何内容。

答案 2 :(得分:0)

如果MySQLdb.connect失败,则不会分配db属性。另外,如果连接到数据库失败,您想要回滚什么?