python常见错误之 TypeError: object() takes no parameters和AttributeError: 'my_db' object has no attribute 'conn'

最近在做数据库连接测试,用了MySQLdb库,但是在封装类的时候一直报错AttributeError: 'my_db' object has no attribute 'conn'。

找了好久,百思不得其解,郁闷!

首先,一直是在初始化函数中直接用connect方法连接,没有传值。

然后一直找不到错在哪里,然后把代码修改,在初始化函数中用传参的方法,这次报错信息变化了报 TypeError: object() takes no parameters

接下来我就查这个错的解决方案,解决如下:

二大原因,新手必过坑之一

1. __init__ 你以为写对了,其实错了,因为是左右都是2个下划线。是左边两个!!右边也是两个!!!不是合计2个!!!

2.init写成Int

 

最后恍然大悟,我的init写错了,写成int了

最终修改代码如下:

 1 import MySQLdb
 2 
 3 
 4 class MyABC_db():
 5     def __init__(self):
 6         self.conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', password='root',
 7                                     database='testcases',
 8                                     charset='utf8')
 9         # self.cursor = self.conn_db.cursor()
10 
11     def close(self):
12         self.conn.close()
13 
14     def select_record(self, query):
15         cursor = self.conn.cursor()
16         cursor.execute(query)
17         c = cursor.fetchall()
18         return c
MySQLdb
 1 from Code.myabc_db import MyABC_db
 2 
 3 if __name__ == '__main__':
 4     # host = '127.0.0.1'
 5     # port = 3306
 6     # user = 'root'
 7     # password = 'root'
 8     # db = 'testcases'
 9     # charset = 'utf8'
10     sl = MyABC_db()
11     ql = 'select * from codenumber'
12     result = sl.select_record(ql)
13     print(result)
runpc

 

posted on 2021-09-01 15:05  橙子HQ  阅读(1266)  评论(0)    收藏  举报