[英]Using a class without calling the constructor in python
I have simple class to fetch query from database . 我有简单的类可以从数据库中获取查询。
# myClass.py
class DB:
def __init__ (self, host, user, password):
self.conn = MySQLdb.connect("localhost","****","****","***")
self.conn.set_character_set('utf8mb4')
cursor = self.conn.cursor()
cursor.execute('SET NAMES utf8mb4;')
cursor.execute('SET CHARACTER SET utf8mb4;')
cursor.execute('SET character_set_connection=utf8mb4;')
def query(self, q):
cursor = self.conn.cursor()
cursor.execute(q)
return cursor
If I use the below query with it works ok, 如果我使用下面的查询可以正常工作,
from myClass import DB
q = DB("..", "..", "..", "..")
_fetch = q.query("... ")
However if I would like to get rid of the second line since I am declaring user, pass, host .. in myClass.py 但是,如果由于我要声明第二行而希望摆脱第二行,请在myClass.py中传递host ..
So, when I try 所以,当我尝试
from myClass import DB
_fetch = DB.query("... ")
it won't allow me to connect, even if I remove the self,
keyword for query 即使删除
self,
关键字,它也不允许我连接
You could try something like: 您可以尝试类似:
# myClass.py
# code will be executed only once a the first import
conn = MySQLdb.connect("localhost","****","****","***")
conn.set_character_set('utf8mb4')
cursor = conn.cursor()
cursor.execute('SET NAMES utf8mb4;')
cursor.execute('SET CHARACTER SET utf8mb4;')
cursor.execute('SET character_set_connection=utf8mb4;')
class DB:
# class attribute shared among all DB instance
cursor = conn.cursor()
# class method
@classmethod
def query(cls, q):
cls.cursor.execute(q)
return cursor
You can create class object ones and then just import and use it: 您可以创建类对象,然后导入并使用它:
# myClass.py
class DB:
def __init__ (self, host, user, password):
# ...
db = DB("..", "..", "..", "..") # Create object ones.
Somewhere in other module: 其他模块中的某处:
from myClass import db
db.query("... ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.