从父级实例化子类而不更改父代码

时间:2013-05-13 07:56:24

标签: python class inheritance instantiation

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

  

somemodule.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() 
  

othermodule.py

from somemodule import parentclass

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

        super(childclass, self).__init__()

问题是,我想要修补父类,所以它会调用子类的构造函数,而不更改 somemodule.py 的代码。 它是否只在类实例(这是更好的)或全局修补并不重要。

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

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用mock.patch

class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()