简体   繁体   中英

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!

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.

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