简体   繁体   中英

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

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

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("... ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM