Bastiaan
Bastiaan

Reputation: 4672

Override a class method when it is returned from a function call

I know how to override class methods (an-introduction-to-classes-and-inheritance-in-python) but sometimes you get a class object as an instance returned from a function call (do I say this correctly?) Now want to change one of the methods of such returned instance (or the whole class for that matter). How do I do this? I know one can override instance methods as described in this answer, but it's said that is not a clean way of doing it.

My case:

import pyodbc
import logging

class MyDataBase(object):

    def __init__(self):
        self.db = pyodbc.connect(cnxn_str)
        self.cur = self.db.cursor()
    # Now I want to override the cursor method execute

    def self.cur.execute(self, sql_str):
        logging.debug(sql_str)
        super(cursor.execute)

Obviously this code is not quite right, consider it pseudo code. Question really is how to enhance the execute method for the cursor object. Thanks for your help!

Upvotes: 0

Views: 191

Answers (1)

Dane Hillard
Dane Hillard

Reputation: 900

This sounds like a prime case for using decorators, or you could just write a method in MyDataBase that takes the SQL string as an argument, logs it, then calls self.cur.execute. This would be the preferred way, in my opinion, over extending/overriding a third party object.

Upvotes: 1

Related Questions