Skip to main content

Python Inheritance

Python inheritance is an ability to provide utilization of one class properties to another class . this property is like that of a class data and function attributes. Super class (base class, parent class) is a class that are provide properties. and inherit this property by other class is called derived class(sub class, child class).

class BaseClass: #parent class
  #statements
  #body of class
#inherit Baseclass
class DrivedClass(BaseClass): #child class
  #statements
  #body of class

For example

class Opps: #Base class
  def javaProgram(self):
    print("Java Programming")
  def cppProgram(self):
    print("CPP Programming")  
class Programming(Opps): #derived class
  def test(self):
    print("Programming test")
    #access base class function
    self.cppProgram() 
    
obj=Programming()
obj.test()
#call to base class function
obj.javaProgram()
Output
Programming test
CPP Programming
Java Programming
Inherit base class to derived

Note that base class have 2 functions. when inherited the properties of base class (oops) to derived class (programming) . using of derived class object are capable to use properties of base class.

We can check the class instance (object) of using isinstance() function. let see another example.

class Processor: #base class
  pass
class Memory(Processor): #derived
  pass

obj=Memory()
#check class instance
print(isinstance(obj,Processor))
print(isinstance(obj,Memory)) 
print(isinstance(obj,str))  
Output
True
True
False

In this example obj is instance of both Memory and processor class. so isinstance() function are return the result of True. In last case str class are not inherit by Memory class then result are display false.

Multiple inheritance in python

When more than one base class are inherited by a derived class that process is called multiple inheritance. here given an example.

class School: #base class
  def fatchName(self):
    self.name="Python Programming"
  def fatchCertificat(self):
    self.credit="Python Training OO7"

class Course: #base class
  def subject(self):
    print("Learn Programming")

class Student(School,Course):#derived
  def __init__(self,name):
    self.studen_name=name 
  def destination(self):
    self.subject()
    self.fatchCertificat()
    self.fatchName()
    print("Student Name :",self.studen_name)
    print("School :",self.name)
    print("Certificat :",self.credit)

coder=Student("Foo")
coder.destination()
Output
Learn Programming
Student Name : Foo
School : Python Programming
Certificat : Python Training OO7
Múltiple inheritance example

In this example student class are inherit two different class properties. in similar way inherit multiple base class.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment