Where does the value of the variable in the subclass go?

Viewed 43
class A(object):
    def __init__(self, x):
        self.x = x

    def f(self, x):
        return 2*x

    def g(self, x):
        return self.f(x)
        
class B(A):
    def g(self, y):
        return 3*y + self.x

class C1(B):
    def __init__(self, x, y):
        B.__init__(self,x)
        self.y = y

    def f(self, x):
        return self.x + self.y

class C2(B):
    def __init__(self, x, y):
        B.__init__(self,x)
        self.y = y

    def f(self, x):
        return x + self.x + self.y

a = A(5)
b = B(2)
c1 = C1(3,5)
c2 = C2(3,5)

When I do "What does the expression c2.f(4) evaluate to?", I was not sure where self.x in the f function in class C2 points to.

Could you give me some suggestions?

1 Answers

c2.f(4) makes 12. The value of x in function f is 4 because that is the argument in c2.f(4). The value of c2's self.x is 3 because C2 inherits from B, which inherits from A, where the line self.x = x occurs. In this line, x is what is entered in the line c2 = C2(3,5) and because it is assigned to self.x, c2's self.x is 3. Because of the line self.y = y in class C2, the instance c2's y value is what is entered in the line c2 = C2(3,5), 5. 4 + 3 + 5 makes 12.

Related