Python call constructor in a member function

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!

Answers


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.


Need Your Help

How to configure Myfaces to log through logback

jsf logging jsf-2 myfaces

How do I configure Myfaces to write to the logs through logback implementation which rest of my application uses ? Currently I'm writing logs from all parts of my application except the messages by

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.