简体   繁体   English

从函数调用返回时重写类方法

[英]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). 我知道如何重写类方法( python中的类和继承 ),但是有时您会得到一个类对象,作为从函数调用返回的实例(我正确地说了吗?)现在想更改此类返回实例的方法之一(或更改整个类)。 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. 真正的问题是如何增强游标对象的execute方法。 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 . 这听起来像是使用装饰器的最佳案例,或者您可以在MyDataBase中编写一个将SQL字符串作为参数的方法,将其记录下来,然后调用self.cur.execute This would be the preferred way, in my opinion, over extending/overriding a third party object. 我认为,这是扩展/覆盖第三方对象的首选方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM