Classes In Python : Within the Classes of Python we can store methods and variables. Classes are defined by the keyword class as shown below.
Inheritance : Inheritance is one of the most important characteristics of Object Oriented programming. In Inheritance we will create new classes or child classes by inheriting the classes from parent class or base class.
Inheritance Example In Python :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Vehicle: def ParentOfAllVehicles(self): print 'Is an parent of all the vehicles' def Start(self): print 'Will start moving' def Stop(self): print 'Will stop moving' class Car(Vehicle): def AutomaticStart(self): print 'Will start without any instructions' d=Car() d.ParentOfAllVehicles() d.Start() d.Stop() d.AutomaticStart() |
OUTPUT:
Inheritance Example In Python
Explanation of Inheritance Example : In the above example, House is known as Super class when a new house is purchased, it will have Carparking, PowerBackup properties and Interior is known as child class which will add extra features like interior designing, furnishing. Child class inherits the properties of super class. Here child class Interior inherits the properties of carParking, powerBackup and also wants to do furnishing and Interior Design also.
Overriding : Overriding can be defined as redefining the functionality of super class in Sub class is known as method Overriding.
Overriding Example In Python :
Super class :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class A(): def __init__(self): print ("Super class has started executing") def method1(self): print("method1 function is executing") |
sub class :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class B(A): def __init__(self): print("Sub class has started executing") def method1(self): print("Class B has modified the existing method of Method1") ref = B() ref.method1() |
OUTPUT:
Overriding Example In Python
Explanation of Overriding Example : Here in the class A is known as Super class. Where in there is a constructor and a method(method1) available. So now class B wants to inherit the properties of Class A and wants to redefine the method(method1) in its own style or according to Class B needs. Hence it will override the method(method1) and write its implementation.