PWP - Chapter 5
PWP - Chapter 5
Introduction:
• Python follows object oriented programming paradigm. It deals
with declaring python classes and objects which lays the
foundation of OOP’s concepts.
• Python programming offers OOP style programming and provides
an easy way to develop programs. It uses the OOP concepts that
makes python more powerful to help design a program that
represents real world entities.
• Python supports OOP concepts such as Inheritance, Method
Overriding, Data abstraction and Data hiding.
class counter:
self.__secretcount+=1
c1=counter()
c1.count()
Output:
count= 1
count= 2
Traceback (most recent call last):
class student:
s1=student()
print("b=",s1.b)
s1.public_method()
Output:
b= 20
a= 10
Creating Constructor:
def __init__(self):
# body of the constructor
class student:
def __init__(self,rollno,name,age):
self.rollno=rollno
self.name=name
self.age=age
p1=student(11,"Ajay",20)
Roll No of student= 11
Age No of student= 20
Programs:
Define a class rectangle using length and width.It has a method which can
compute area.
class rectangle:
def __init__(self,L,W):
self.L=L
self.W=W
def area(self):
return self.L*self.W
r=rectangle(2,10)
print(r.area())
Output
20
Create a circle class and initialize it with radius. Make two methods
getarea and getcircumference inside this class
class circle:
def __init__(self,radius):
self.radius=radius
def getarea(self):
return 3.14*self.radius*self.radius
def getcircumference(self):
return 2*3.14*self.radius
c=circle(5)
print("Area=",c.getarea())
print("Circumference=",c.getcircumference())
Output:
Area= 78.5
Circumference= 31.400000000000002
Types of Constructor:
class student:
def __init__(self):
def show(self,name):
print("Hello",name)
s1=student()
s1.show("World")
Output:
Hello World
class student:
count=0
def __init__(self):
student.count=student.count+1
s1=student()
s2=student()
Output:
The parameterized constructor take its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are provided by the
programmer.
class student:
def __init__(self,name):
self.name=name
def show(self):
print("Hello",self.name)
s1=student("World")
s1.show()
Output:
Hello World
Destructor:
A class can define a special method called destructor with the help of _ _del_ _().
It is invoked automatically when the instance (object) is about to be destroyed.
class student:
def __init__(self):
def __del__(self):
print("Destructor called")
s1=student()
s2=student()
del s1
Output:
Destructor called
Method Overloading:
• Method overloading is the ability to define the method with the same name
but with a different number of arguments and data types.
• With this ability one method can perform different tasks, depending on the
number of arguments or the types of the arguments given.
• Method overloading is a concept in which a method in a class performs
operations according to the parameters passed to it.
• As in other language we can write a program having two methods with same
name but with different number of arguments or order of arguments but in
python if we will try to do the same we get the following issue with method
overloading in python.
Example-
# To calculate area of rectangle
def area(length,breadth):
calc=length*breadth
print(calc)
# To calculate area of square
def area(size):
calc=size*size
print(calc)
area(3)
area(4,5)
Output-
area(4,5)
• Python does not support method overloading i.e it is not possible to define
more than one method with the same name in a class in python.
• This is because method arguments in python do not have a type. A method
accepting one argument can be called with an integer value, a string or a
double as shown in example.
Example-
class demo:
def print_r(self,a,b):
print(a)
print(b)
obj=demo()
obj.print_r(10,'S')
obj.print_r('S',10)
Output:
10
S
S
10
• In the above example same method works for two different data types.
• It is clear that method overloading is not supported in python but that
does not mean that we cannot call a method with different number of
arguments. There are couple of alternatives available in python that
make it possible to call the same method but with different number of
arguments.
class demo:
def arguments(self,a=None,b=None,c=None):
print("3 arguments")
elif a!=None:
print("1 argument")
else:
print("0 arguments")
obj=demo()
obj.arguments("Amol","Kedar","Sanjay")
obj.arguments("Amit","Rahul")
obj.arguments("Sidharth")
obj.arguments()
Output-
3 arguments
2 arguments
1 argument
0 arguments
Example 2: With a method to perform different operations using method
overloading
class operation:
def add(self,a,b):
return a+b
op=operation()
Output-
Inheritance is the capability of one class to derive or inherit the properties from
some another class.
The new class is called derived class or child class and the class from which
this derived class has been inherited is the base class or parent class. The benefits
of inheritance are:
Class A:
# Properties of class A
Class B(A):
name="Maruti"
def display(self):
print("Name= ",self.name)
price=400000
def disp_price(self):
print("price= ",self.price)
car1=category()
car1.display()
car1.disp_price()
Output:
Name= Maruti
price= 400000
def __init__(self,name,price):
self.name=name
self.price=price
def display(self):
print("Name= ",self.name)
def __init__(self,name,price):
def disp_price(self):
print("price= ",self.price)
car1=category("Maruti",400000)
car1.display()
car1.disp_price()
car2=category("Honda",600000)
car2.display()
car2.disp_price()
Output:
Name= Maruti
price= 400000
Name= Honda
price= 600000
Multilevel Inheritance:
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and grandfather.
Syntax:
Class A:
# Properties of class A
Class B(A):
Class C(B):
#Mutilevel Inheritance
class c1:
def display1(self):
print("class c1")
class c2(c1):
def display2(self):
print("class c2")
class c3(c2):
def display3(self):
print("class c3")
s1=c3()
s1.display3()
s1.display2()
s1.display1()
Output:
class c3
class c2
class c1
# Base class
class Grandfather:
grandfathername =""
def grandfather(self):
print(self.grandfathername)
# Intermediate class
class Father(Grandfather):
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Father):
def parent(self):
# Driver's code
s1 = Son()
s1.grandfathername = "Srinivas"
s1.fathername = "Ankush"
s1.parent()
Output:
GrandFather : Srinivas
Father : Ankush
Multiple Inheritance:
When a class can be derived from more than one base classes this type of
inheritance is called multiple inheritance. In multiple inheritance, all the features of
the base classes are inherited into the derived class.
Syntax:
Class A:
# variable of class A
# functions of class A
Class B:
# variable of class B
# functions of class B
Class C(A,B):
# Class C inheriting property of both class A and B
# Base class1
class Father:
def display1(self):
print("Father")
# Base class2
class Mother:
def display2(self):
print("Mother")
# Derived class
class Son(Father,Mother):
def display3(self):
print("Son")
s1 = Son()
s1.display3()
s1.display2()
s1.display1()
Output:
Son
Mother
Father
Hierarchical Inheritance:
When more than one derived classes are created from a single base this type of
inheritence is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
# Base class
class Parent:
def func1(self):
# Derived class1
class Child1(Parent):
def func2(self):
# Derived class2
class Child2(Parent):
def func3(self):
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
Method Overriding:
To override a method in base class, we must define a new method with sam
name and same parameters in the derived class.
class A:
def display(self):
def display(self):
Output-
The super() method gives you access to methods in a super class from the
subclass that inherits from it.
The super() method returns a temporary object of the superclass that then
allows you to call that superclass’s method.
class A:
def display(self):
class B(A):
def display(self):
super().display()
print("This is derived class")
Output-
Composition Classes:
Syntax:
Class GenericClass:
Instance_variable_of_generic_class=GenericClass
Some_method(instance_varable_of_generic_class)
• For example, we have three classes email, gmail and yahoo. In email class
we are referring the gmail and using the concept of composition.
Example:
class gmail:
def send_email(self,msg):
class yahoo:
def send_email(self,msg):
class email:
provider=gmail()
def set_provider(self,provider):
self.provider=provider
def send_email(self,msg):
self.provider.send_email(msg)
client1=email()
client1.send_email("Hello")
client1.set_provider(yahoo())
client1.send_email("Hello")
Output:
• In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing
logic in place.
class A:
def display(self):
class B(A):
def display(self):
A.display(self)
Output:
Super
subclass
Inheritor
Replacer
Extender
default
Provider
class super:
def method(self):
def delegate(self):
class inheritor(super):
pass
def method(self):
print("in replacer.method")
def method(self):
super.method(self)
print("in extender.method")
def action(self):
print("in provider.action“)
klass().method()
print("\n provider...")
x=provider()
x.delegate()
Output:
inheritor...
in super.method
provider...
replacer...
in replacer.method
provider...
extender...
in super.method
in extender.method
provider...
in provider.action
• When we call the delegate method through
provider instance, two independent inheritance searches occur:
• On the initial x.delegate call, Python finds the delegate method in Super, by
searching at the provider instance and above. The instance x is passed into
the method's self argument as usual.