In: Computer Science
Inheritance - Method Calls
Consider the following class definitions.
class C1(): def f(self): return 2*self.g() def g(self): return 2 class C2(C1): def f(self): return 3*self.g() class C3(C1): def g(self): return 5 class C4(C3): def f(self): return 7*self.g() obj1 = C1() obj2 = C2() obj3 = C3() obj4 = C4()
For this problem you are to consider which methods are called when the f method is called. Because the classes form part of an inheritance hierarchy, working out what happens will not always be straightforward.
For each of obj1, obj2, obj3, and obj4, print out the methods which will be called following a call to objn.f(). You should print a single line in the format: objn: call1, call2, call3.
So for example, when obj1.f() is called, you should print:
obj1: C1.f, C1.g
We’ve already done this for you to give you an example.
Note: You don’t need to actually call the methods, you just need to write a print statement, as for obj1.f() above. All you need are the four print statements.
---------- USING PYTHON ----------
PYTHON CODE:
class C1():
def f(self):
return 2*self.g()
def g(self):
return 2
class C2(C1):
def f(self):
return 3*self.g()
class C3(C1):
def g(self):
return 5
class C4(C3):
def f(self):
return 7*self.g()
# creating object for class C1,C2,C3,C4
obj1 = C1()
obj2 = C2()
obj3 = C3()
obj4 = C4()
# print statements displaying the method call hierarchy for
obj1,obj2,obj3,obj4
print("obj1: C1.f, C1.g")
print("obj2: C2.f, C1.g")
print("obj3: C1.f, C3.g")
print("obj4: C4.f, C3.g")
SCREENSHOT FOR CODING:
explanation:
For obj1:
if obj1.f() is executed, both method f() and g()
will be invoked from C1.
so C1.f,C1.g
For obj2:
Class C2 inherits C1. So there is no g() method in
C2.
so,obj2.f() is executed, f() from Class C2 and g()
method
from class C1 is invoked.
so C2.f,C1.g
For obj3:
class C3 inherits C1. So there is no f() method in
C3.
so obj3.f() is executed, f() from class C1 will be
invoked
and g() from c3 will be invoked.
so C1.f,C3.g
For obj4:
class C4 inherits C3. so There is no g() method in
C4.
so obj4.f() is executed, f() from class C4 will be
invoked
and g() from c3 will be invoked.