Python Inheritance Tutorial | Inheritance In Python with Examples


What is Inheritance in Python?


Inheritance is the ability of one class to inherit the attributes and methods of another, something that allows us to reuse code and make programming much more optimal. It is a powerful feature in object-oriented programming.

To see its usefulness, in this lesson we will develop an example. We will start from a class without inheritance with many attributes and we will break it down into other simpler classes that allow us to work better with your data.

Python inheritance syntax


class BaseClass:
Base class body
class Derived Class (Base Class):
Derived class body

The derived class inherits characteristics of the base class, adding new features. This results in code reuse.


What is Inheritance in Python?


Inheritance in Python with Example


Many years ago I found myself in need of designing a structure for a store that sold three types of products: ornaments, food and books.

All products in the store had a series of common attributes, such as reference, name, pvp ... but some were specific to each type.

If we start from a class that contains all the attributes, it would be more or less like this:

class  Product :

    def  __init__ ( self ,  reference ,  type ,  name ,
                 pvp ,   description ,  producer = None ,
                 distributor = None ,  isbn = None ,  author = None ):
        self . reference  =  self reference
        . type = self type . name = self name .
       
        pvp  =  pvp
        self . description  =  self description
        . producer = self producer . distributor = self distributor . isbn = isbn self . author = author
       
ornament  =  Product ( '000A' , 'ORNAMENT' , 'Ornate Glass' , 15 ,
                  'Porcelain glass with drawings' )

print ( ornament )
print ( ornament . type )
Outcome
Obviously this is a nonsense, so let's see how to take advantage of the inheritance to improve the approach.

Get success in your career as a Python Programmer by being a part of the Python Training Institute in Bangalore.

Comments

Popular posts from this blog

Python Programming Language Introduction - How to learn Python for Beginners?

Interesting Facts About Python Programming Language

Python Comments Tutorial | Types of Python Comments