Unit – 5
Object Oriented Programming
Programming Paradigm: Paradigm can also be termed as a method to solve some problems or do some task. Programming paradigm is an approach to solve problems using some programming language or we can say, it is a method to solve a problem using tools and techniques that are available to us following some approach.
Programming Paradigm is divided into two categories
1) Imperative Programming Paradigm
2) Declarative Programming Paradigm
Imperative Programming Paradigm :
a)Oldest
b) It features close relation to machine architecture.
c) Based on Von-Neuman architecture
Disadvantage :
a) Complex problem cannot be solved
b) Less efficient and less productive
c) Parallel programming is not possible
Eg) C, Fortran, Basic
Procedural Programming Paradigm
a) Emphasis on procedure in terms of underlying machine model
b) No difference between procedural and imperative approach
c) It has the ability to reuse the code and it was boon at that time when it was in use because of its reusability
Eg: C, C++, Java, Pascal
The program is written as a collection of classes and object which are meant for communication. The smallest and basic entity is object and all kind of computation is performed on the object only
a) More emphasis on data rather than procedure.
b) It can handle almost all kind of real life problem.
Advantage :
a) Data Security
b) Inheritance
c) Code reusability & flexibility
d) Abstraction
Eg: C++, Java, Python, Ruby, Simula
(Simula is the first OOP language).
Important features of OOP are:
a) Inheritance
b) Polymorphism
c) Data hiding
d) Encapsulation
e) Overloading
f) Reusability
g) Methods & message passing
h) Delegation
Before seeing OOP features it's important to understand the basic entity of OOP ie class and object.
What is Class?
a) In Python everything is an object.
b) To create objects we required some model or plan or blueprint which is nothing but class.
c) We can write a class to represent properties(attributes) and actions(behaviour) of objects.
d) Properties can be represented by variables.
e) Action can be represented by methods.
f) Hence class contains both variables & method.
How to define a Class?
We can define a class using ‘class’ keyword.
Syntax: class ClassName();
Or classClassName:
Ex)
Class Student;
“‘This is the class for student data ”’
print(student__doc__) #prints the documentation
help(student) #displays the documentation
#of modules, functions, classes etc
#keywords etc
Within the python class we can represent data by using variables.
3 types of variables are allowed:
1) Instance variables (object level variables)
2) Static variables (class level variables)
3) Local variables (method level variables)
Within the python class we can represent operations by using methods. The following are the types of allowed methods:-
1) Instance methods
2) Class methods
3) Static methods
Examples of class:
Class Student |
‘“SAE Kondhwa student data”’ |
det__init__(self): |
self.name=’Nitin’ |
self.rollno=’77’ |
def.display(self): |
print(“Hello I am ”: self.name) |
print(“My rollno is ”: self.rollno) |
What is object?
Physical existence of a class is nothing but object. We can create any number of object
Syntax to create object |
reference variable = classname() |
Wrt our example code |
s= Student() |
Note: Here ‘s’ is the reference variable which is used to refer object. By using reference variable we can access the properties and methods of objects.
So after writing class as in given code we can instantiate an object of a student class as follows and access the method ‘display’ of a class.
=Student() #object creation |
s.display() #calling method through |
#reference variable |
|
O/P Hello I am : Nitin |
My roll no is:77 |
a) Methods are the function which belongs to some or one class
b) Methods can return a value to the caller, can be passed as an argument and can be an object and can be assigned to some other variable
Inheritance: Inheritance is most important pillar in OOP concepts
Inheritance is the capability of one class to derive or inherit the propertied from some another class
We have different types of inheritance in OOP as follows
1) Simple Inheritance (Single Inheritance)
2) Multiple Inheritance
3) Multilevel Inheritance
4) Hybrid Inheritance
5) Hierarchical Inheritance
Flow:
1) Simple Inheritance
Where A & B are the classes (one child & one parent)
|
2) Multiple Inheritance
Multiple parents but common child class.
3) Multilevel Inheritance:
Here a is base class or super class
B is derived from A and C is derived from B
C holds all the properties of class A & B
4) Hybrid Inheritance
Hybrid inheritance is an inheritance which represents all inheritances at some stages.
It’s a combination of all types of inheritances
5) Hierarchical Inheritance
One parent can have multiple child classes or in other words multiple child classes are derived from one base class.
Inheritance Example code:
Class Polygon: |
det__int it__()self, no_of_sides): |
self.in = no_of_sides |
self.sides = [0 for i in range (no_of_sides)]; |
|
det inputsides(self): |
self.sides = [float (input(‘Enter side’ + str(i+1)+ ” : ” )) for i in range |
(self in)] |
detdispsides(self): |
for i in range(self.in): |
print (‘Side’, i+1, ‘is’ ,self.sides[i] ) |
|
Class Triangle: |
det__init__(self): |
polygon__init__(self,3) |
|
Det findArea(self): |
a, b, c= self.sides |
#now calculate semi parameter |
S= (a+b+c) / 2 |
area= (s*(s-a)*(s-b)*(s-c)**0.5) |
print (‘The area of triangle is %0.2f ’ % as ) |
|
t=Triangle() |
t.inputsides() |
t.dispSides() |
Polymorphism :
Polymorphism means that different types respond to the same function.
Polymorphism is very useful as it makes programming more initiative and therefore easier
It’s a funny word that just means the same function is defined on object of different types
Eg)
Code1: print (len(‘SAE Kondhwa’)) #for string
print (len([10,20,30])) # for list
Here same function ‘len’ used for different parameters.
Eg
Code2: def add(x, y, z=5)
Return x+y+z
print (add(3, 4,))
print (add(4, 5, 6))
O/P : 12
15
Here user defined function ‘add’ takes different numbers of parameters.
Containership :
Containership also referred to are a composition allows a class to contain an object of a different class as a member data.
Ex: Class A could contain an object of class B as a member. Here all the public methods(or functions) defined in B can be executed within the class A. A becomes the container, while class B becomes the container class.
This can also be explained as class A is composed of class B
Inheritance represents an ‘is-a’ relationship in OOP, but containership represents ‘has-a’ relationship.
Reusability :
Reusing code is key to building a maintainable system.
And when it comes to reusing code in Python, it all starts and ends with humble function. Take some lines of code, give them a name, and you have got a function (which can be reused).
Delegation :
Delegation mean that you use an object of another class as an instance variable, and forward message to the instance.
It is better than inheritance for many cases because it makes you to think about each message you forward, because the instance is of a known class, rather than a new class and It doesn’t force you to accept all the methods of the superclass :
You can provide only the methods that really make sense.
Delegation can be viewed as a relationship between objects where one object, called its delegate.
Data abstraction :
Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.
Whereas, data encapsulation is one of the fundamentals of OOP it refers to the bundling of the data with the methods that operate on data. Encapsulation is used to prevent access from unauthorized data available inside the class.
Encapsulation :
In an object oriented python program, we can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation.
Eg: We create a class car which has two methods drive() and update Software(). When a car object is created, it will call the private method
updateSoftware()
Classes: As discussed earlier in python everything's an object. To create an object we are required some model or plan or blueprint which is nothing but class.
Objects: Physical existence of a class is nothing but object. We can create any number of objects for a class.
Self is the default variable which is always printing to current object (like ‘this’ keyword in Java)
By using self we can access instance variables and instance methods of objects
Important :
1) ’Self ’ should be first parameter in method called constructor.
Eg) def__init__(self);
2) ‘Self ‘ should be first parameter inside instance methods.
Eg) def talk (self):
Constructor will be executed automatically at the time of object creation.
The main purpose of main constructor is to declare & initialize instance variables
Per object constructor will be executed only once.
Constructor should have at least one argument
(atleast_’self’ )
Constructor is optional and if we are not providing any constructor then python will provide default constructor.
1) Instance Variable :
If a value of a variable varies from object to object, then such type of variables are called instance variables or object variable.
For every object, separate copy of instance variables will be created
Instance variable can be created using class objects.
2) Static Variable :
If the value of the variable is not varied from object, such types of variables we have to declare with in the class directly but outside of method such type of variable we have to declare with in the class directly but outside of method such type of variable are called state variables
For total class only one copy of static variable created and shared by all objects of that class.
We can access static variables either by class name or by object reference. But recommended to use class name.
Note :
In the case of instance variables for every object a separate copy will be created,but in the case of static variables for total class only one copy will be created & shared by every object of that class.
Classical object oriented languages, such as C++, Java, control the access to class resources by public, protected and private key words
Python doesn’t have any mechanism that effectively restricts access to any instance variable or method
Python prescribes convention of prefixing the name of variable/method with single or double underscore to emulate the behaviour of protected and private access specifiers.
All members in a python class are public by default. Any members in a python class are public by default. Any member can be accessed from outside the class environment.
Ex) Public attribute :
Python performs name mangling of private variables.
Every member with double underscores will be changed to _object, _class, __variable. If so required, it can still be access from outside the class, but the practise should be retained.
>>> e= Employee(‘Nitin’, 20000) |
>>> e= Employee__salary |
20000 |
>>> e= Employee__salary= 10000 |
>>> e= Employee__salary |
10000 #modified |
Class Employee:
det___init__(self, name, salary);
self.name = name
Self.salary = salary
>>>e= Employee(‘Nitin’ , 10000)
>>>e._salary = 20000 #still can modify
>>>e._salary
20000
Similarly, a double underscore__prefixed to a variable makes it private. It gives a strong suggestion not to touch it from outside the class.
Any attempt to do so will result in an AttributeError :
Ex) Private Attributes:
Class Employee: |
det__init (self, name, sal) : |
self__name = name # private |
self__salary = sal # private |
|
>>> e= Employee(‘Nitin’, 20000) |
>>>e.__salary = 10000 #cause error |
Attribute Error: ‘Employee’ object has no attribute ‘__salary’ |
Reference Books
- R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
- Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
- Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
- Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
- Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810