0

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!

Community
  • 1
  • 1
Bastiaan
  • 4,451
  • 4
  • 22
  • 33
  • 1
    Why do you think you need to do this? Im certain there is a better way. – Daniel Roseman Oct 13 '14 at 17:37
  • As the accepted answer to the other question says, what is "not clean" is the *concept* of changing a method on just one instance of a class. If you need to do it, you can do it as shown in another answer to that question, but you're not going to find a "nice" way to do it because it's not really a nice thing to do. You could instead create your own class that wraps `self.cur`. – BrenBarn Oct 13 '14 at 17:43
  • @DanielRoseman, What would the better way be? – Bastiaan Oct 13 '14 at 19:27
  • @BrenBarn, I'd like to change the whole class, but how do I do if its only returned upon a function call? – Bastiaan Oct 13 '14 at 19:28
  • @Bastiaan: Why do you need to change `cur.execute` instead of just giving your MyDataBase class its own `execute` method that internally does the logging and then calls `cur.execute` behind the scenes? – BrenBarn Oct 13 '14 at 19:30
  • @BrenBarn I'd like to pass on all other methods of the cursor object including all those that I don't quite know of. But ok, considering there isn't much of an answer I guess that's the only way there is. – Bastiaan Oct 14 '14 at 02:55
  • Strange though, all tutorials on class inheritance bloat about how great it is one can add on to existing classes. Now I want to add to pyodbc but can't, just because the class cannot be called directly. – Bastiaan Oct 14 '14 at 18:48

1 Answers1

1

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.

Dane Hillard
  • 890
  • 1
  • 11
  • 27