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.
Inheritance in Python with Example
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
Post a Comment