[英]Why is my Python mysql class __init__ function trying to overload the mysql package __init__ function?
我想为我的 python 脚本创建一个简单的 mysql 连接 class 。 script.py
中 class 的预期用途:
import db_connection
db = db_connection.DBConnection()
db.get_cursor()
class 本身在脚本db_connect.py
中:
import mysql.connector
class DBConnection:
def __init__(self):
self.__host="192.168.1.22"
self.__port="3306"
self.__user="somename"
self.__passwd="somepw"
self.__database="mydbname"
def __connect(self):
con = mysql.connector.connect(
self.__host,
self.__port,
self.__user,
self.__passwd,
self.__database
)
print("connected.")
return con
def get_cursor(self):
con = self.__connect()
cursor = con.cursor(dictionary=True)
return cursor
我收到以下错误:
Traceback (most recent call last):
File "C:/.../script.py", line 14, in <module>
db.get_cursor()
File "C:\...\db_connection.py", line 26, in get_cursor
con = self.__connect()
File "C:\...\db_connection.py", line 13, in __connect
con = mysql.connector.connect(
File "C:\...\Python\Python38-32\lib\site-packages\mysql\connector\__init__.py", line 219, in connect
return MySQLConnection(*args, **kwargs)
File "C:\...\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 64, in __init__
super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 6 were given
Process finished with exit code 1
There seems to be an issue with the init function in my class and the mysql package init function. 我对 Python 太不熟练了,无法理解我做错了什么,因此非常感谢您的帮助。
毫无疑问,您的班级的__init__
方法隐藏了MySQLConnection
的方法。 问题是您将 arguments 作为位置 arguments 传递,而mysql.connector.connect
要求将它们作为关键字 ZDBC11CAA5BDA28E7DAD77 传递
con = mysql.connector.connect(
host=self.__host,
port=self.__port,
user=self.__user,
password=self.__passwd,
database=self.__database
)
您也可以参考文档中的一些示例。
正如 Matthias 所指出的,这里不需要两个前导下划线(在普通用户编写的代码中很少需要)。 要将这些变量标记为 class 的内部变量,您通常会使用单个下划线,即:
def __init__(self):
self._host="192.168.1.22"
self._port="3306"
self._user="somename"
self._passwd="somepw"
self._database="mydbname"
你得到一个进一步的错误
ReferenceError:弱引用 object 不再存在
因为您的连接只是临时的,并且存在于get_cursor
方法的 scope 中。 连接在该方法结束时关闭。 您可以通过将连接存储在 class 上来解决此问题,它保留对打开连接的引用,例如:
class DBConnection:
def __init__(self):
self._host="192.168.1.22"
self._port="3306"
self._user="somename"
self._passwd="somepw"
self._database="mydbname"
self.con = None
def _connect(self):
self.con = mysql.connector.connect(
host=self._host,
port=self._port,
user=self._user,
password=self._passwd,
database=self._database
)
print("connected.")
def get_cursor(self):
if not self.con:
self._connect()
return self.con.cursor(dictionary=True)
有关此ReferenceError
的更多详细信息,请参阅“弱引用 object 不再存在”是什么意思? .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.