0

首先,这是我的(伪)代码:

一些模块.py:

class parentclass(object):
    def __init__(self):
        if(not prevent_infinite_reursion) #Just to make shure this is not a problem ;)
            self.somefunction()

    def somefunction():

        # ... deep down in a function ...

        # I want to "monkey patch" to call constructor of childclass, 
        # not parentclass
        parentclass() 

其他模块.py

from somemodule import parentclass

class childclass(parentclass):
    def __init__(self):
        # ... some preprocessing ...

        super(childclass, self).__init__()

问题是,我想修补父类,所以它会调用childclass的构造函数,而不更改somemodule.py的代码。是否仅在类实例中修补(这更好)或全局修补都没有关系。

我知道我可以覆盖somefunction,但它包含太多代码行,因为这是理智的。

谢谢!

4

1 回答 1

3

您可以为此使用mock.patch

class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()
于 2013-05-13T08:36:08.290 回答