Inheritance in Python

Inheritance

  1. Creating new class using an existing class.
  2. Existing class is a Base/Super class which contains General Properties.
  3. New Class is a Derived/Sub class which will have General Property and its own Special Property.
  4. Types
    1. Single
    2. Multiple Level
    3. Hierarchical
    4. Multiple

Single Inheritance

It has One Base class and One Derived class.

Syntax:

class A:
// Members
class B(A):
//Members

Example: Single Inheritance

# Python Single Inheritance Example

#Base class declaration
class Account:
def __init__(self,accno, acnm):

self._accno=accno #protected member
self._accname=acnm

#Derived class declaration
class SBAcct(Account):

def __init__(self,accno,acnm,minbal):

Account.__init__(self,accno,acnm) #calling the base class constructor
self.__minbal_=minbal

def showSBInfo(self):

print(“Account Information : “)
print(“Account no : “, self._accno)
print(“Account Holder Name :”, self._accname)
print(“Minimum Balance :”, self.__minbal_)

#creating the object of the Subclass
print(“Example – Single Inheritance”)
objsb1=SBAcct(2004, “Sanjay”, 4000.00)
objsb1.showSBInfo()

objsb2=SBAcct(2005, “Vijaya”, 5000.00)
objsb2.showSBInfo()

Hierarchical Inheritance
It contains one base class and multiple Derived Classes.

# Python Hierarchial Inheritance Example
#Base class declaration

class Account:

def __init__(self,accno, acnm):

self._accno=accno
self._accname=acnm

#Derived class declaration
class SBAcct(Account):

def __init__(self,accno,acnm,minbal):

Account.__init__(self,accno,acnm) #calling the base class constructor
self.minbal=minbal

def showSBInfo(self):

print(“SB Account Information”)
print(“Account no :”, self._accno)
print(“Current Balance :”, self.minbal)

class Loan(Account):

def __init__(self,accno,acnm,loanamt,term):

Account.__init__(self,accno,acnm) #calling the base class constructor

self.loanamt=loanamt
self.term=term

def showLoanInfo(self):

print(“Loan Account Information”)
print(“Account no :”, self._accno)
print(“Loan Amount :”, self.loanamt)

#creating the object of the Subclass
print(“Example – Hierarchical Inheritance “)
objsb1=SBAcct(2004, “Sanjay”, 4000.00)
objsb1.showSBInfo()

objLoan1=Loan(2005, “Sanjay”, 10000.00, 3)
objLoan1.showLoanInfo()

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile