Python Inheritance

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and a printname method:

 
class Person:
  def __init__(self, fname, lname):
    
  self.firstname = fname
    self.lastname = lname

  
  def printname(self):
    print(self.firstname, 
  self.lastname)

#Use the Person class to create an object, and then 
  execute the printname method:

x = Person("John", "Doe")

  x.printname()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from the Person class:

 
class Student(Person):
  pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

Now the Student class has the same properties and methods as the Person class.

Inheritance in Python

Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of inheritance are:  

Below is a simple example of inheritance in Python  

 # A Python program to demonstrate inheritance 
   
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is 
# equivalent to "class Person(object)"
classPerson(object):
       
    # Constructor
    def__init__(self, name):
        self.name =name
   
    # To get name
    defgetName(self):
        returnself.name
   
    # To check if this person is an employee
    defisEmployee(self):
        returnFalse
   
   
# Inherited or Subclass (Note Person in bracket)
classEmployee(Person):
   
    # Here we return true
    defisEmployee(self):
        returnTrue
   
# Driver code
emp =Person("Geek1")  # An Object of Person
print(emp.getName(), emp.isEmployee())
   
emp =Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
 Geek1 False
Geek2 True

 

What is object class? Like Java Object class, in Python (from version 3.x), object is root of all classes. In Python 3.x, “class Test(object)” and “class Test” are same. In Python 2.x, “class Test(object)” creates a class with object as parent (called new style class) and “class Test” creates old style class (without object parent). Refer this for more details.

For more, checkout W3Schools and Geeks For Geeks.