Home > Net >  Subclass Unable to Access Instance Variable Defined by Parent Class
Subclass Unable to Access Instance Variable Defined by Parent Class

Time:12-28

I have created 3 classes which are as follows:

  1. A having a1,a2 as class vairiables
  2. B(A) A is the parent for B, having b1,b2 as class Variables
  3. C(B) B is the parent for C, having c1, c2 as the class Variables

I am trying to create an Object for the C(B) class by typing:- obj = C(1,2)

But I am not able to access the class A, B variables (a1,a2,b1,b2) using the object created from the C class.

class A:
    def __init__(self,a1,a2):
        self.a1 = a1
        self.a2 = a2
    def testa():
        print('inside A')

class B(A):
    def __init__(self,b1,b2):
        self.b1 = b1
        self.b2 = b2
    def testb():
        print('inside B')

class C(B):
    def __init__(self,c1,c2):
        self.c1 = c1
        self.c2 = c2
    def testc():
        print('inside C')


obj = C(1,2)

CodePudding user response:

You have to make the classes communicate. Here are two alternatives.

Alternative 1

class A:
    def __init__(self, a1, a2): 
        self.a1 = a1
        self.a2 = a2
        print('inside A')

class B(A):
    def __init__(self, b1, b2):
        super().__init__(b1, b2)
        self.b1 = b1
        self.b2 = b2
        print('inside B')

class C(B):
    def __init__(self, c1, c2):
        super().__init__(c1, c2)
        self.c1 = c1
        self.c2 = c2
        print('inside C')


obj = C(1, 2)
print(obj.a2, obj.a1)  # -> 2 1
print(obj.b2, obj.b1)  # -> 2 1
print(obj.c2, obj.c1)  # -> 2 1

Alternative 2

class A:
    def __init__(self, a1, a2):
        self.a1 = a1
        self.a2 = a2
        print('inside A')

class B(A):
    def __init__(self, b1, b2, a1, a2):
        A.__init__(self, a1, a2)
        self.b1 = b1
        self.b2 = b2
        print('inside B')

class C(B):
    def __init__(self, c1, c2, b1, b2, a1, a2):
        B.__init__(self, b1, b2, a1, a2)
        self.c1 = c1
        self.c2 = c2
        print('inside C')


obj = C(6, 5, 4, 3, 2, 1)
print(obj.a2, obj.a1)  # -> 1 2
print(obj.b2, obj.b1)  # -> 3 4
print(obj.c2, obj.c1)  # -> 5 6
  • Related