Inheritance concept in Python

05 min read

 Inheritance is a mechanism for creating a new class that specializes or modifies the behaviours of an existing class. The original class is called a base class or a superclass. The new class is called the derived class or a subclass. When a class is created via inheritance, it "inherits" the attributes defined by its base classes. However, a derived class may redefine any of these attributes and add new attributes of its own.

Inheritance is specified with a comma-separated list of base-class names in the class statement. If there is no logical base class, a class inherits from object. An object is an abstract data type that is the root of all Python objects and provides the default implementation of common methods such as __new__(), which creates a new instance. Inheritance can be explained by saying, it's getting something from someone else for a cause in the program. 

The following example clearly illustrates a pragmatic implementation of the inheritance concept. In this program, we would like to inherit the last name of the parent to the child.

class parent():                                                        #initialised a class, say class 1
        def print_last_name(self):
                     print('Prep')                                        # consider the last name of the perseon to be prep
class child(parent):                                             # class 1 is inherited into this class now
        def print_first_name(self):
                         print('FACE')                                  # define a function to print the first name

placements = child()                                           # object created
placements.print_first_name()                     # first name and second name is printed
placements.print_last_name()

Output:

FACE
Prep


It is also to be noted that, the inheritance can be overwritted, i.e if the last name was changed in the inherited class then the latest last_name would have been printed.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error