使用类而不在python中调用构造函数

时间:2016-03-16 13:24:30

标签: python python-3.x

我有一个简单的类来从数据库中获取查询。

# 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

如果我使用以下查询,它可以正常工作,

from myClass import DB
q = DB("..", "..", "..", "..")
_fetch = q.query("... ")

但是,如果我想摆脱第二行,因为我在myClass.py

中声明用户,传递,托管..

所以,当我尝试

from myClass import DB
_fetch = DB.query("... ")

即使我删除self,查询关键字

,它也不会允许我进行连接

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方式:

# 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

答案 1 :(得分:0)

您可以创建类对象,然后只需导入并使用它:

# myClass.py
class DB:
    def __init__ (self, host, user, password):
        # ...

db = DB("..", "..", "..", "..")  # Create object ones.

其他模块的某处:

from myClass import db

db.query("... ")