关于python:从父类实例化子类而不更改父代码

Instantiate children class from parent without changing parent code

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

somemodule.py:

1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
5
6
7
from somemodule import parentclass

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

        super(childclass, self).__init__()

问题是,我想对父类进行monkey修补,所以它将调用childclass的构造函数,而不更改somemodule.py的代码。它只在类实例中(这是舒尔更好的)或全局中进行修补并不重要。

我知道我可以重写某个函数,但它包含太多代码行,因为这是正常的。

谢谢!


您可以使用mock.patch:

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