Python Interview Questions on Classes and Inheritance

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Classes and Inheritance

Modules

  • Modules are used to create a group of functions that can be used by anyone on various projects.
  • Any file that has python code in it can be thought of as a Module.
  • Whenever we have to use a module we have to import it into the code.
  • Syntax:

import module_name

Object Orientation

  • Object Orientation programming helps in maintaining the concept of reusability of code.
  • Object-Oriented Programming languages are required to create readable and reusable code for complex programs.

Classes

  • A class is a blueprint for the object.
  • To create a class we use the Keyword class.
  • The class definition is followed by the function definitions, class class_name:

def function_name(self):

Components of a class
A class would consist of the following components:

  1. class Keyword
  2. instance and class attributes
  3. self keyword
  4. __init__function

Instance and class attribute

Class attributes remain the same for all objects of the class whereas instance variables are parameters of__init__( ) method. These values are different for different objects.

The self

  • It is similar to this in Java or pointers in C++.
  • All functions in Python have one extra first parameter (the ‘self’) in the function definition, even when any function is invoked no value is passed for this parameter.
  • If there a function that takes no arguments, we will have to still mention one parameter – the “self’ in the function definition.
    The__init__( ) method:
  • Similar to the constructor in Java
  • __init__( ) is called as soon as an object is instantiated. It is used to
    initialize an object.

Question:
What will be the output of the following code?

class BirthdayWishes:
   def__init__(self, name):
        self.name = name
   def bday_wishes(self):
        print("Happy Birthday ", self.name,"!!")
bdaywishes = BirthdayWishes("Christopher")
bdaywishes.bday_wishes( )

Answer:

The output will be as follows:
Happy Birthday, Christopher !!

Question:
What are class variables and instance variables?
Answer:

Class and instance variables are defined as follows:

 class Class_name:
     class_variable_name = static_value

     def__init__(instance_variable_val):
           Instance_variable_name = instance_ variable val

Class variables have the following features:

  • They are defined within class construction
  • They are owned by the class itself
  • They are shared by all instances in class
  • Generally have the same value for every instance
  • They are defined right under the class header
  • Class variables can be accessed using the dot operator along with the class name as shown below:

Class name. class_variable_name

The instance variables on the other hand:

  • Are owned by instances.
  • Different instances will have different values for instance variables.
  • To access the instance variable it is important to create an instance of the class:

instance_name = Class_name( )
instance_name. Instance variable name

Question:
What would be the output of the following code:

class sum_total:
      def calculation(self, number1,number2 = 8,):
         return number1 + number2
st = sum_total( )
print(st.calculation(10,2))

Answer:

12

Question:
When is__init__( ) function called ?
Answer.
The__init__( ) function is called when the new object is instantiated.

Question:
What will be the output of the following code?

class Point:
   def__init__(self, x=0,y=10,z=0):
        self.x = x + 2
        self.y = y + 6
        self.z = z + 4
p = Point(10, 20,30)
print (p.x, p.y, p.z)

Answer:

12 26 34

Question:
What will be the output for the following code?

class StudentData:
    def__init__(self, name, score, subject):
         self.name = name
         self.score = score
         self.subject = subject
    def getData(self):
         print("the result is {0}, {1}, {2}".
format(self.name, self.score, self.subject))
sd = StudentData("Alice",90,"Maths")
sd.getData( )

Answer:

the result is Alice, 90, Maths

Question:
What will be the output for the following code?

class Number__Value:
    def init (self, num):
      self.num = num 
      num = 500
num = Number_Value(78.6)
print(num.num)

Answer:

78.6

Inheritance

Object-Oriented languages allow us to reuse the code. Inheritance is one such way that takes code reusability to another level altogether. In an inheritance, we have a superclass and a subclass. The subclass will have attributes that are not present in the superclass. So, imagine that we are making a software program for a Dog Kennel. For this, we can have a dog class that has features that are common in all dogs. However, when we move on to specific breeds there will be differences in each breed.

So, we can now create classes for each breed. These classes will inherit common features of the dog class and to those features, it will add its own attributes that make one breed different from the other. Now, let’s try something. Let’s go step by step. Create a class and then create a subclass to see how things work. Let’s use a simple example so that it is easy for you to understand the mechanism behind it.

Step 1:
Let’s first define a class using the “Class” Keyword as shown below:

class dog( ):

Step 2:
Now that a class has been created, we can create a method for it. For this example, we create one simple method which when invoked prints a simple message I belong to a family of Dogs.

def family(self):
      print("I belong to the family of Dogs")

The code so far looks like the following:

class dog( ):
      def family(self):
            print("I belong to the family of Dogs")

Step 3:
In this step we create an object of the class dog as shown in the following code:

c = dog( )

Step 4:
The object of the class can be used to invoke the method family( ) using the dot ‘.’ operator as shown in the following code:

c.family( )

At the end of step 4 the code would look like the following:

class dog( ):
   def family(self):
       print("I belong to the family of Dogs")

c = dog( )
c.family( )

When we execute the program we get the following output:

I belong to the family of Dogs

From here we move on to the implementation of the concept of inheritance. It is widely used in object-oriented programming. By using the concept of inheritance you can create a new class without making any modification to the existing class. The existing class is called the base and the new class that inherits it will be called the derived class. The features of the base class will be accessible to the derived class.
We can now create a class german shepherd that inherits the class dog as shown in the following code:

class germanShepherd(dog):
     def breed(self):
         print ("I am a German Shepherd")

The object of a class german shepherd can be used to invoke methods of the class dog as shown in the following code:

Final program
class dog():
     def family(self):
           print ("I belong to the family of Dogs")
class german shepherd(dog):
    def breed(self) :
           print ("I am a German Shepherd")
c = germanShepherd!)
c.family( )
c.breed( )

Output

I belong to the family of Dogs 
I am a German Shepherd

If you look at the code above, you can see that object of class germanShepherd can be used to invoke the method of the class.
Here are few things that you need to know about inheritance.
Any number of classes can be derived from a class using inheritance.
In the following code, we create another derived class Husky. Both the classes germaShepherd and husky call the family method of dog class and breed method of their own class.

class dog( ):
   def family(self):
       print("I belong to the family of Dogs")

class germanShepherd(dog):
    def breed(self):
         print("I am a German Shepherd")

class husky(dog):
   def breed(self):
       print("I am a husky")
g = germanShepherd()
g.family()
g. breed()
h = husky ()
h. family()
h .breed()

Output

I belong to family of Dogs 
I am a German Shepherd 
I belong to family of Dogs 
I am a husky

A derived class can override any method of its base class.

class dog( ):
   def family(self):
       print ("I belong to family of Dogs")

class germanShepherd(dog):
    def breed(self):
        print("I am a German Shepherd")
class husky(dog):
    def breed(self):

print("I am a husky")
def family(self):
print ("I am class apart")
g = germanShepherd()
g.family()
g. breed()
h = husky ()
h. family() h.breed()

Output

I belong to the family of Dogs 
I am a German Shepherd 
I am class apart 
I am a husky

A method can call a method of the base class with the same name.

Look at the following code, the class husky has a method family( ) which call the family( ) method of the base class and adds its own code after that.

class dog( ):
  def family(self):
        print("I belong to family of Dogs")

class germanShepherd(dog):
   def breed(self) :
      print ("I am a German Shepherd")

class husky(dog):
   def breed(self):
       print("I am a husky")
   def family(self):
        super().family()
       print("but I am class apart")

g = germanShepherd( )
g.family( )
g. breed( )
h = husky( )
h. family( ) h.breed( )

 

Output

I belong to the family of Dogs 
I am a German Shepherd 
I belong to the family of Dogs 
but I am class apart 
I am a husky

Question:
What are multiple inheritances?
Answer:
If a class is derived from more than one class, it is called multiple inheritances.

Question:
A is a subclass of B. How can one invoke the__init__function in B from A?
Answer:
The__init__function in B can be invoked from A by any of the two methods:

  • super( ).__init__( )
  • __init__(self)

Question:
How in Python can you define a relationship between a bird and a parrot.
Answer:
Inheritance. Parrot is a subclass of birds.

Question:
What would be the relationship between a train and a window?
Answer:
Composition

Question:
What is the relationship between a student and a subject?
Answer:
Association

Question:
What would be the relationship between a school and a teacher?
Answer:
Composition

Question:
What will be the output for the following code:

class Twice_multiply:
def __init__(self):
self.calculate (500)

def calculate(self, num):
self.num = 2 * num;
class Thrice_multiply(Twice_multiply):
def__init__(self):
super ( ) .__init__( )
print("num from Thrice_multiply is", self. num)

def calculate(self, num):
self.num = 3 * num;
tm = Thrice_multiply()

Answer:

num from Thrice_multiply is 1500
>>>

Question:
For the following code is there any method to verify whether tm is an object of Thrice_multiply class?

class Twice_multiply:
   def__init__(self) :
       self.calculate(500)
   def calculate(self, num) :
        self.num = 2 * num;
class Thrice_multiply(Twice_multiply):
    def __init__(self) :
      super () .__init__()
      print("num from Thrice_multiply is", self. num)
def calculate(self, num):
     self.num = 3 * num;
tm = Thrice_multiply( )

Answer:
Yes, one can check whether an instance belongs to a class or not using isinstance( ) function.

isinstance(tm,Thrice_multiply)