linusg linusg - 7 months ago 10
Python Question

Override method of class in another file

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"

Answer

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.