Python call constructor in a member function

2019-07-19 03:39发布

问题:

Let's take for example this class, which is extending MySQLDB's connection object.

class DBHandler(mysql.connections.Connection):
    def __init__(self,cursor=None):
        if cursor == None:
            cursor = 'DictCursor'

            super(DBHandler,self).__init__(host = db_host,
              user = db_user,
              passwd = db_pass,
              db = db,
              cursorclass=getattr(mysql.cursors, cursor))


    def getall(self,q,params=None):
        try:
           cur = self.cursor()
           cur.execute(q,params)
           res = cur.fetchall()
           return res
         except mysql.OperationalError:
            #this is the line in question
            pass


    def execute(self,q,params):
        cur = self.cursor()
        cur.execute(q,params)
        self.commit()
        return cur.lastrowid

This thing is largely a convenience to get simpler access to common required queries.

On the line marked with the comment, is it possible in Python to recall the object constructor, even though this is a member function? I use this example to illustrate because it would effectively reestablish the connection in the event it is dropped on timeout before a query is run.

I'm aware of MySQLdb's ping() method, this is really just a question of capability. In python, Is it possible to call a constructor from within a member function called on an instance to re-initialize that instance? Thanks!

回答1:

Yes, you can, since it would be preferable to extract your initialization code in another method (a def init(self):).

This is because __init__ is not really the constructor of the object, it is more the "initializer" of your instance, the real constructor is the __new__ method, that is responsible of the instance creation.