Override method of class in another file

2019-09-23 16:05发布

问题:

Say I have two files, file1.py and file2.py. In file1.py, I define two classes, one inherits from the other:

file1.py:

class Class1:
    def __init__(self):
        pass

    def func1(self):
        return "Hello world!"

class Class2(Class1):
    def __init__(self):
        pass

    def func2(self):
        return self.func1()

So now I'm able to call func1() and func2() from Class2.

file2.py:

import file1

class Class3(file1.Class2):
    def __init__(self):
        pass

Question: How can I change func1() from Class1 in file2.py, so that func2() in Class2 returns the same as func1()?

So not like this:

class Class3(file1.Class2):
    ...
    def func1(self):
        return "Another string"

回答1:

Would overriding func1 work?

class Class(file1.Class2):
    def func1(self):
        print "Class3.func1"

c = Class3()
c.func2()

Since func2 is not defined in Class3, Class2.func2 is called. However, in the body of that function, self is still an instance of Class3, so self.func1() calls Class3.func1, not Class1.func1. That is different from

d = Class2()
d.func2()

where self in Class2.func2 is an instance of Class2. Class2 does not define func1, so Class1.func1 is called.



回答2:

I think you want to monkeypatch Class1.func1.

c2 = Class2()
print(c2.func2())
Hello world!

def new_func1(self):
    return "Another string"

Class1.func1 = new_func1  # This is monkey patching.

print(c2.func2())
Another string

But this might break other code that uses Class1 or Class2.