Featured

    Featured Posts

Python OOPS Tutorial 8:Inheritance In Python




Inheritance In Python




 §  In the given above, figure there is two classes in this, the name of one is C1and the 
       name of the other is C2. Explain that how c2 class can consume the features of c1.

 §  We are using some approach here.

 §  In First approach C2 class needs to create all the properties in its which is in the class C1.but in this approach c2 needs to be redefined all the properties which is already 
      defined by c1 class.

 §  In Second approach C2 class needs to create an object of C1 class.

 §  In Third approach C3 can consume the properties of C1 by establishing parent-child relationship








 §  The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.

 §  Inheritance is the technique which allows us to inherit the data members and methods from base class to derived class.

 §  Inheritance in Python is a mechanism in which one object acquires all the properties and behaviours of parent object.

 §  The idea behind inheritance in Python is that you can create new class that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new method and fields also.

Important points

  • In the inheritance the class which is give data members and methods is known as base or super or parent class.
  • The class which is taking the data members and methods is known as sub or derived or child class.
  • The data members and methods of a class are known as features.
  • The concept of inheritance is also known as re-usability or extendable classes or sub classing or derivation.
  • With inheritance, all the members of super class are available to the subclass object.

Syntax of Python Inheritance



class BaseClass(Object):
            body_of_base_class

class DerivedClass(BaseClass): 
            body_of_derived_class




When We Should go For Inheritance

§  Suppose we want to develop a school management project.
§  When we create a project, we will have to see which of these entities is possible in that project and Then the list out the property of the entity
  §  suppose in our project there are some entity possible which are Student,TeachingStaff,NonTeachingStaffe will check which entity is possible in this Project.

Student:

- Id
-Name
-Address
-Phone
-Class
-Fees
-Grade
-Marks

TeachingStaff:

 - Id 
-Name
-Address
-Phone
-Qualification
-Subject
-salary
-Designation

NonTeachingStaff

- Id
-Name
-Address
-Phone
-Dname
-MgrId
-Salary
-Designation


Add caption

 §  Some Property is common in all entity; therefore, it is not right to define common 
     property separately in each entity.

 §  The common property should be defined in a different common place and whoever 
       needs it, inherit it.

§  In this way Common Property will not have to do define separately everywhere. and  
   we can reuse all those property which are already define by someone.

Types of Inheritance

·         Based on number of ways inheriting the feature of base class into derived class we 
      have five Inheritance type they are:

  • Single inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Multilevel inheritance
  • Hybrid inheritance

Single inheritance

§  In single inheritance there exists single base class and single derived class.

class Car:
    #class Attribute
    Type1= "Four wheeler"
    def read(self):
        self.name="Maruti"
    def show(self):
        print(self.name)
        print(Car.Type1)

class Bike(Car):
    #class attribute
    Type2 = "Two wheeler"
    def read1(self):
        self.name="HONDA"
    def show1(self):
        print(self.name)
        print(__class__.Type2)

#Crating a Base class Object
print('With Respect to Base Object')
c=Car()
c.read()
c.show()
#Crating a Derived class Object
print('With Respect to Derived Object')
bike=Bike()
bike.read()
bike.show()
bike.read1()
bike.show1()


 v When We create Child class object which class constructor is invoked.
 §  When we create child class object child class constructor is invoked. If we want to  
c         all parent class constructor   before calling child class constructor then we need to 
          use super() method in the child class constructor. Super refer the parent class object.

class C1:
    def __init__(self):
        print('C1-Class Constructor!')

class C2(C1):
    def __init__(self):
        print('C2-class Constructor!.')
#creating child class object
obj=C2()
output:
C2-class Constructor!.

v Now we are using super(). __init__ () in the child class constructor as a first line.



class C1:

    def __init__(self):
        print('C1-Class Constructor!')

class C2(C1):
    def __init__(self):
        super().__init__()
        print('C2-class Construtor!.')

#creating child class object
obj=C2()

output:
C1-Class Constructor!
C2-class Constructor!.



v Initializing parent class data-member during the child class object creation.
§  How we can pass value from child class constructor to the parent-class constructor.
§  We can pass value from child class constructor to the parent class constructor using 
     super().__init__(value1,value2,…..)


class C1:
    def __init__(self,a):
        print('C1-Class Constructor!')
        self.a=a

class C2(C1):
    def __init__(self,a,b):
        super().__init__(a)
        print('C2-class Construtor!.')
        self.b=b
    def display(self):
        print('a = ',self.a,'b= ',self.b)

obj=C2(10,20)
obj.display()


Example:-





class User:
    def __init__(self,name,age,mno):
        self.name=name
        self.age=age
        self.mno=mno
class Employee(User):
    def __init__(self,name,age,mno,specialization):
        super().__init__(name,age,mno)
        self.specialization=specialization

class Manager(User):
    def __init__(self,name,age,mno,department):
        super().__init__(name,age,mno)
        self.department=department


#Create a Employee Object
e1=Employee('John',30,9897675432,'Python Prog')
print('......Employee Details......')
print('Name = ',e1.name)
print('Age = ',e1.age)
print('Mno = ',e1.mno)
print('Specialization = ',e1.specialization)
print('--------------------------------------')
m1=Manager('Harry',45,8989767645,'Sales')
print('......Manager Details......')
print('Name = ',m1.name)
print('Age = ',m1.age)
print('Mno = ',m1.mno)
print('Department =',m1.department)



Multilevel inheritances



·         In Multilevel inheritances there exists single base class, single derived class and multiple intermediate base classes.

Single base class + single derived class + multiple intermediate base classes.

Intermediate base classes


·         An intermediate base class is one in one context with access derived class and in another context same class access base class.

 v GrandParent, Parent and Child are the perfect example to represent Multilevel 
        Inheritance in Python.




class GrandParent:
    def __init__(self):
        print('Grandparent Constructor!.')

    def displayGrandParent(self):
        print('Grandparent Method!.')

class Parent(GrandParent):
    def __init__(self):
        print('Parent Constructor!.')
    def displayParent(self):
        print('parent Method!.')

class Child(Parent):
    def __init__(self):
        print('Child Constructor!.')
    def displayChild(self):
        print('Child Method!.')


#Create Child class Object
obj=Child()
obj.displayGrandParent()
obj.displayParent()
obj.displayChild()

       

Multiple inheritance

§  In multiple inheritance there exist multiple classes and single derived class.
§  Python provides us the flexibility to inherit multiple base classes in the child class.

class Base1:
    -classBody-
class Base2:
    -classBody-
class BaseN:
    -classBody-

class Derived(Base1,Base2,....BaseN):
    -classBody-


class Calculation1: 
    def Summation(self,a,b):
        return a+b;
class Calculation2: 
    def Multiplication(self,a,b):
        return a*b;
class Calculator(Calculation1,Calculation2): 
    def divide(self,a,b):
        return a/b;

c=Calculator()
print('Sum= ',c.Summation(10,20))
print('Mul= ',c.Multiplication(10,20))
print('Division= ',c.divide(10,2))
   

Python issubclass
§   Python issubclass() is an inbuilt method .
§   By using issubclass()  method we can check whether one class is sub-class of another class or not.
§   This method takes two parameter if first-parameter is the sub-class of second parameter then it will return True otherwise it will return false.
Syntax
issubclass(object, classinfo)
Here are the following parameters.
object:  is the class to be checked.
classinfo: is a class, tuple, or type of a class

Example-1:-
class Test1:
    pass

class Test2(Test1):
    pass

print('Test1 is Sub-class of Test2 - ',issubclass(Test1,Test2))
print('Test2 is Sub-class of Test1 - ',issubclass(Test2,Test1))
Output:
Test1 is Sub-class of Test2 -  False
Test2 is Sub-class of Test1 -  True


Example2:

#Creating superclass
class Bank:
    pass

#Creating subclass
class SBI(Bank):
    pass

#Creating sub class of SBI
class HDFC (SBI):
    pass

#Now we will check subclass with different arguments

#Checking if SBI is subclass of Bank or not
print(issubclass(SBI,Bank)) #The Output:True

#Checking if Bank is subclass of SBi or not
print(issubclass(Bank, SBI)) #The Output:False

#Checking multilevel subclass
print(issubclass(HDFC, Bank)) #The Output:True

#Checking if a class is subclass of itself or not
print(issubclass(HDFC,HDFC)) #The Output:True

#checking with an object argument
#Here object is referred to base class always
print(issubclass(Bank, object))#The Output:True


Python isinstance()
 §  By using isinstance() function  we can check whether if the object (first argument) is 
       an instance or subclass of classinfo class (second argument).

 §  This method takes two parameters if first-parameter is an instance or sub-class of second parameter then it will return True otherwise it will return false.

 v Using Python isinstance(), you can do the followings:
 §  Check the type of a Python variable is of a given type.
 §  Verify whether a variable is a number or string.
 §  Check if an object is an instance of a specified class.
 §  Check whether variable or object is of dict type, list type, set type, tuple type.

v isinstance() with Built-in Types

 §  Python provides number of Different built-in types such are Numbers, List, Tuple, Strings, Dictionary. Most of the time you want to check the type of a value to do some operations on it. In this case, isinstance() function is useful.

 §  In this example, we are using isinstance() function to check instance with the String type, number type, dict type, list type
Example1:-

a=10
b=20.5
c='hello'
d=[10,20,30]
e=(40,50,60)
f={70,80,90}
print(a,'is an instance of int->',isinstance(a,int))
print(b,'is an instance of float->',isinstance(b,float))
print(c,'is an instance of str->',isinstance(c,str))
print(d,'is an instance of int->',isinstance(d,list))
print(e,'is an instance of int->',isinstance(e,tuple))
print(f,'is an instance of int->',isinstance(f,set))

Output:
10 is an instance of int-> True
20.5 is an instance of float-> True
hello is an instance of str-> True
[10, 20, 30] is an instance of int-> True
(40, 50, 60) is an instance of int-> True
{80, 90, 70} is an instance of int-> True


v How can we check that a variable can store multiple types?

 §  Suppose we have a variable and we have to check that the variable has a numeric value or not where the numeric value can be int or float.

 §  You can check this variable with multiple types. To do this, you need to mention all 
       types in a tuple and pass it as the isinstance’s classInfo argument.
a=10
b=20.5
print(a,'is an instance of int or float->',isinstance(a,(int,float)))
print(b,'is an instance of int or float->',isinstance(b,(int,float)))
a=20.5
b=10
print(a,'is an instance of int or float->',isinstance(a,(int,float)))
print(b,'is an instance of int or float->',isinstance(b,(int,float)))

Output:
10 is an instance of int or float-> True
20.5 is an instance of int or float-> True
20.5 is an instance of int or float-> True
10 is an instance of int or float-> True
v isinstance() with Python Class

 §  By using isinstance() function we can check whether given object is  specified class 
        type or not. If the object is an instance of the given class type then it will return True 
       otherwise False.
Example1:-
class Person:
    pass

class Employee:
    pass

emp=Employee()
if isinstance(emp, Employee):
    print("Yes! given object is an instance of class Employee\n")
else:
    print("No! given object is not an instance of class Employee")

p=Person()
if isinstance(emp, Person):
    print("Yes! given object is an instance of class Employee\n")
else:
    print("No! given object is not an instance of class Employee")

Output:
Yes! given object is an instance of class Employee
No! given object is not an instance of class Employee


v isinstance function with an inheritance
 §  As we know the object of the subclass type is also a type of parent class.

 §  For example, If Car is a subclass of Vehicle then the object of Car class can be 
       referred by either Car or Vehicle.Then isinstance(carObject, Vehicle) will return true.

 §  The isinstance function works on the principle of the is-a relationship. The concept of 
       an is-a relationship is based on class inheritance.

Example1:-
class Test1:
    pass

class Test2(Test1):
    pass

t1=Test1()
t2=Test2()

print('t1 is the Instance  of Test1 - ',isinstance(t1,Test1))
print('t1 is the Instance of Test2 - ',isinstance(t1,Test2))
print('t2 is the Instance  of Test2 - ',isinstance(t2,Test2))
print('t2 is the Instance of Test1 - ',isinstance(t2,Test1))
Output:
t1 is the Instance of Test1 - True
t1 is the Instance of Test2 - False
t2 is the Instance of Test2 - True
t2 is the Instance of Test1 - True

v Extracting only Same type value from given List.

 §  Extracting only all numeric values from given list.
list=[10,20,'java','python',30.5,40.2,'php']
numericList=[]
stringList=[]
for item in list:
    if isinstance(item,(int,float)):
        numericList.append(item)
    elif isinstance(item,str):
        stringList.append(item)
print("String List :-", stringList)
print("Number List :-", numericList)
Output:
String List: - ['java', 'python', 'php']
Number List: - [10, 20, 30.5, 40.2]







author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews