Python Practice Multi-Level Inheritance Instance Variables

In this class, We discuss Python Practice Multi-Level Inheritance Instance Variables.

For Complete YouTube Video: Click Here

These examples will help the reader to improve their coding skills.

Take the complete placement course and practice tests to crack the campus placement exams easily.

Try to solve the examples on your own, then check for a solution.

Q1)
What is the output displayed by the below program?

class Parent:
    cval=20
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def Method1(self):
        self.cval=self.x+self.y#here we are creating new instance variable
        print(Parent.cval)
    def Method2(self):
        print(self.x)
        print(self.y)
obj=Parent(10,20)
obj.Method1()

In the above program, a new instance variable cval is created in the method.

The point to understand: We can create instance variables using the method. Not only with constructors.

The output of the program is 20.

Q2)
What is the output displayed by the below code?

class Parent:
    cval=20
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def Method1(self):
        self.cval=self.x+self.y
        print(Parent.cval)
    def Method2(self):
        print(self.x)
        print(self.y)
        print(self.cval)
class Child(Parent):
    cval=1 #each class has its own
    def Method3(self):
        Child.cval=self.x+self.y
        print(Child.cval)
    def Method4(self):
        print(Parent.cval)
obj=Child(10,20)
obj.Method3()
obj.Method1()
obj.Method2()
obj.Method4()

In the above program, We used the concept of inheritance.

To know the basics of inheritance, click here.

The inherited class has the same class variable name.

Point to understand: Each class can have its class variables.

Given below is the output displayed by the program.

Output:
30
20
10
20
30
20
Q3)
What is the output displayed by the below code?

class Parent:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def method1(self):
        z=self.x+self.y
        print(z)
class Child(Parent):
    def method2(self):
        z=self.x+self.x
class Subchild(Child):
    def __init__(self,x,y,z):
        super().__init__(x,y)
        self.z=z
    def method1(self):
        super().method1()# this point has to be undersstood
        self.z=self.z+self.y
        print(self.z)
obj=Subchild(1,2,5)
obj.method1()

In the above program, we are using multi-level inheritance.

Point to understand: The super() method is calling method1, which is not present in the above level of inheritance.

Suppose the method is not found in the immediate above level. It will check for the next level and so on.

Below is the output displayed by the program.

3
7