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

Modifiers in Python

Modifers are key words used in class, variable, method and constructor declarations. It decides the scope and visibility of these declarations.

  1. public  – members are accessible outside the class
  2. private – members are accessed only side the class
  3. protected – members are accessed by same class and its sub classes.

[Note: Real time applications Class, Method and Constructors will be public and Variables will be private. It is used to implement Encapsulation concept in Object Oriented programming.]

Python class members are public by default.  No keywords are used to represent modifiers in Python. Modifiers will be specified by using some Techniques.

private Variable Declaration in Python

self.__empno_=2004   Use two underscore before the variable name and one underscore after the variable name.

Example: Mofidiers in Python

#class declaration
class Car:
# default constructor
def __init__(self):
self.model = “Maruthi”
self.__color_ = “Red”
# private variable cannot accessed from outside the class
# In python is implemented by using name mangling concept

def showCarInfo(self):
print (“Car Details”)
print (“Car Model :”, self.model)
print(“Car Color : “, self.__color_)

#object creation
objC2=Car()
objC2.showCarInfo()

objC2.model=”Santro”
# Accessing the private variable from outside the class
objC2.__color_=”Green”
objC2.showCarInfo()

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

Methods and Constructors in Python

What is a Constructor?

  • Special type of method with the same name as that of the class name
  • Used to assign the value to the variable during the object creation
  • __init__() keyword is used define the constructor in Python

Type of Constructors

  • Default Constructor
    • Takes no parameter
    • Defined by the class or by the user
  • Parameterized Constructor
    • Takes Parameter
    • Defined by the user

Example for Default Constructor

#class declaration
class Laptop:

#Default constructor
def __init__(self):

self.brand=”HP”
self.color=”Black”
self.price=50000.00

# method declaration
def showLaptopInfo(self):

print(“Brand :”, self.brand)
print(“Color :”, self.color)
print(“Price :”, self.price)

#object creation
objLp=Laptop() # calling th default constructor

# calling the methods
print(“Example : Default Constructor”)
print(“Laptop Details :”)
objLp.showLaptopInfo()

Example for Parameterized Constructor

#class declaration
class Laptop:

#parametrize constructor
def __init__(self, brand, color, price):

self.brand=brand
self.color=color
self.price=price

# Method declaration
def showLaptopInfo(self):

print(“Brand :”, self.brand)
print(“Color :”, self.color)
print(“Price :”, self.price)

#object creation
objLp=Laptop(“HP”, “Black”, 45000.00)
objLp1=Laptop(“Dell”, “Grey”, 35000.00)

# calling the methods
print(“Example : parameterized constructor”)
print(“Laptop Details :”)
objLp.showLaptopInfo()
objLp1.showLaptopInfo()

Difference Between Methods and Constructors

Method Constructor
1. Name: Each method in the class will have different name 1.Name: Constructor will have the same name as that of the class name.
__init__() keyword is used to define the constructor in python
2. Task

a. To Assign the Value
b. To Print the Output
c. To Perform Calculation and Comparison

2. Task
a. To Assign the Value
3. Takes Parameter [Optional] 3. Takes Parameter [Optional]
4. Returns value after Calculation or Comparison 4. No Return Type
5. Explicitly called using Object 5. Implicitly Called.

 

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

Python Class and Object

Python is a object-oriented programming Language, which is used to implement all OOP concept at the programming level.

Python class is a

  1. Template or a Blue Print
  2. Contains Variables, Methods and Constructors
  3. Variable shows the object Properties and Methods shows Actions performed by the object.

Syntax:
class <classname>:
// class members

Example: 1
# class and objects in python

#class declaration
class Emp:
# method
def assign(self):
self.empno=2008
self.ename=’Sanjay’

def showEmpInfo(self):
print (“Employee Details”)
print (“Employee no : “, self.empno)
print(“Employee name : “,self.ename)

#object creation
objE=Emp()
#calling the method using object
objE.assign()
objE.showEmpInfo()

Example: 2

#class declaration
class Emp:
# method declaration
def assign1(self,empno, empname):
self.empno=empno
self.empname=empname

def showEmpInfo(self):
print (“Employee Details”)
print (“Employee no : “, self.empno)
print(“Employee name : “, self.empname)

#object creation
objE1=Emp()
objE2=Emp()

print(“Example self keyword in python class”)
#calling the method using object
objE1.assign1(2009, “Vijaya”)
objE1.showEmpInfo()

objE2.assign1(2004, “Sanjay”)
objE2.showEmpInfo()

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

Python Module

Module is a collection of classes and Functions in Python. Functions are grouped into module based on its functionality.

Type

  1. Built-in
  2. User Defined

Example – User Defined Module

# Math Module

def add(a,b):
return a+b

def sub(a,b):
return a-b

def prod(a,b):
return a*b

def div(a,b):
return a/b

Save the file as “mathdemo.py”

Program 1
Using the Module

import mathdemo as md

print(“Difference = “, mathdemo.sub(5,3))
print(“Product = “, md.Div(9,3))

Program 2
# calling the module
from mathdemo import *

print(“Sum = “, add(2,3))
print(“Product = “, prod(2,3))

Note: import keyword is used add the module reference to the current Python file.
prefix the module name before the function name.

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

Exception Handling in Python

Exception is a run time error which occurs during the program execution.  Python provides in-built support for handling the runtime error using try-except block.

syntax:

try:
// code which may throw the exception
except:
// exception handler
finally:
// clean up code

try block contains the code which may throw the Exception. except block contains the Exception handler to handle the Exception. finally block code will be executed when the exception is raised or not raised.

Example 1
# Exception Handling
try:
a=int(input(“First Number: “))
b=int(input(“Second Number: “))
c=a/b
print (“Output:”, c)
except Exception:
print(“Number can’t be Divided by 0”)
finally:
print(“There may or may not have been an exception.”)

Note: Exception is built-in class which handles all types of exceptions in Python

Example 2: try with Multiple except block
try:
x = int(input(“Your number: “))
res = 15 / x
print(“Result – “, res)
except ValueError:
print(“You should have given either an character or a float”)
except ZeroDivisionError:
print(“Infinity”)

Note: one except block can handle only one type of exception. to catch more than one type of exception a try block can have multiple except block

Example – 3 try block with else block
try:
a=10/2
print (“Output : “, a)
except ZeroDivisionError:
print(“No. Cann’t be divieded by Zero”)
else:
print(“No Exception”)
Note: else block will be executed whenever there is no exception

Example – 4 try with raise keyword
try:
x=”a”
a=10/x
print (“Output : “, a)
except:
      raise # prints the type of Exception raised by the code

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

Python Complex Datatypes

Python Complex data types

  1. List
  2. Tuple
  3. Dictionary

List

  1. Group of Values belong different data type enclosed in [ ] bracket
  2. Value is called as item or Element
  3. Each Element will be retrieved based on the position.

List Operation

  1. Indexing – Retrieving only one item based on its position
  2. Slicing – Retrieving group of elements sequentially
  3. Repeation – Printing the List specified no. of times.

List Example:
# List creation
empList = [ 2001, ‘Shivani’,2005, ‘Sanjay’, 2007, ‘Babu’]
print (“employee Details : \n”, empList)

#Indexing
print(“2nd Position : “, empList[1])

#Slicing
print(“1st to 4th element : “, empList[0:4])

#printing from 2nd element to last element
print(“2nd to last element : “, empList[1:])

#Repeation
print(empList*2)

Tuple

  1. Elements are Enclosed in the round brackets ()
  2. Read only – Values can’t be modified.
  3. Supports all the List operations.

Example – Tuple
# Tuple creation
empTuple = ( 2001, ‘Shivani’,2005, ‘Sanjay’, 2007, ‘Babu’)
print (“employee Details : \n”, empTuple)

#specific element from Tuple
print(“2nd Position : “, empTuple[1])

#printing Range of element
print(“1st to 4th element : “, empTuple[0:4])

#printing from 3nd element to Tuple element
print(“3rd position to Last : “, empTuple[2:])

#printing the Tuple two times
print(empTuple*2)

Dictionary

  1. Elements are stored in Key-Value Format
  2. Key is unique and value can be duplicated
  3. Value will be Retrieved based on the key value.

Example – Dictionary
# Dictionary Creation
empDList = {}
empDList[1002]=”Sanjay”
empDList[1003]=’Sania’
empDList[1005]=’Sowmya’

print (“employee Details : \n”, empDList)
print(empDList.keys()) # prints all the keys
print(empDList.values()) # prints all the values

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