Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

CHAPTER 5: Object Oriented Programming in Python

5.1 Creating Classes and Objects


5.2 Method Overloading and Overriding
5.3 Data Hiding
5.4 Data Abstraction
5.5 Inheritance and Composition Classes
5.6 Customization via Inheritance
- Specializing inherited Methods
Python as an OOP Language:
 Python is an object oriented programming language.
 Unlike procedure oriented programming, where the main emphasis is on functions, object
oriented programming stress on objects.
 Object is simply a collection of data (variables) and methods (functions) that act on those
data.
 And, class is a blueprint for the object.
 An object is also called an instance of a class and the process of creating this object is
 called instantiation.

OOP Concepts in Python:


 Class
 Object
 Methods
 Polymorphism
 Method Overloading
 Method Overriding
 Encapsulation
 Abstraction/Data Hiding
 Inheritance
 Single, Multi-Level, Multiple
 Composition
Creating Classes:
Classes are created by keyword class.
Then provide the name of class followed by a colon(:)
Synatx : class ClassName:

'Optional class documentation string'


#class member variable, methods, functions etc.
E. g.
class myclass:
"This is my second class" a = 10
def func_1():
print('Hello')
Class in Python:
The first string is called docstring and has a brief description about the class. Although not
mandatory, this is recommended.
E.g
class myclass:
“This is a docstring. I have created a new class‟‟
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions.
There are also special attributes in it that begins with double underscores (_ _).
For example, _ _doc_ _ gives us the docstring of that class.

Calling class Attributes:


Attributes are the variables that belong to class which are always public and can be accessed
using dot (.) operator.
Eg.: Myclass.Myattribute
E. g.
class myclass:
"This is my second class" a = 10
def func_1():
print('Hello')
print(myclass._ _doc_ _) #O/P - This is my second class print(myclass.a) #O/P: 10
print(myclass.func_1()) #O/P: Hello
Creating Object:
Object is created by assigning class name to object name as follows:
Eg.: MyObj=MyClass
E. g.
class myclass:
"This is my second class" a = 10
def func_1():
print('Hello')
Obj=myclass

Using Object:
To call the attribute or methods of class, object name with dot operator is used.
E. g.
class myclass:
"This is my second class" a = 10
def func_2(self):
print('Hello')
obj=myclass()
print(obj. doc )
print(obj.a)
obj.func_2()

self:
 Class methods must have an extra first parameter in method definition.
 We do not give a value for this parameter when we call the method, Python provides it.
 If we have a method which takes no arguments, then we still have to have one argument –
the
 self.
 This is similar to „this‟ pointer in C++ and „this‟ reference in Java.
When we call a method of this object as
myobject.method(arg1, arg2),
this is automatically converted by Python into
MyClass.method(myobject, arg1, arg2)

The_init_method : method is similar to constructors in C++ and Java.


 It runs as soon as an object of a class is instantiated.
 The method is useful to do any initialization you want to do with your object.
E.g.
class mech:
def
_ _init_ _(self,name):
print("Welcome to ",name)
m=mech("KKPW")
O/P: Welcome to KKWP
class student:
def_init_(self,roll,name):
self.name=name
self.roll=roll
def disp(self):
print(self.name,self.roll)
obj=student(23,"Ram")
obj.disp()
#O/P Ram 23

Method Overloading:
Like other languages (for example method overloading in C++) do,
python does not supports method overloading.
We may overload the methods but can only use the latest defined method.
e.g
class student:
def disp(self,roll,name):
print(roll,name)
def disp(self):
print("WELCOME")
obj=student()
#obj.disp(23,"Ram")
obj.disp()

Method Overloading:
class overlod:
def fun(self,a,b=None):
print(a)
def fun(self,a,b=None):
print(a,b) obj=overlod() obj.fun(89) obj.fun(23,45)
#O/P:
89 None
23 45

Inheritance:
 Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code
 reusability to the program because we can use an existing class to create a new class
instead of
 creating it from scratch.
 In inheritance, the child class acquires the properties and
 can access all the data members and functions defined in the parent class.
 A child class can also provide its specific implementation to the functions of the parent
class.

Inheritance:
In python, a derived class can inherit base class by just mentioning the base in the bracket after
the derived class name.
Syntax:
class derived-class(base-class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax:
class derived-class(base-class1, base-class2…,base-classn):
<class-suite> >
 Inheritance allows us to define a class that inherits all the methods and properties from
another class.
 Parent class is the class being inherited from, also called base class.
 Child class is the class that inherits from another class, also called derived class.

Types of Inheritance
 Single Level
 Multilevel
 Multiple

Single Inheritance:
Single inheritance enables a derived class to inherit properties from a single parent class, thus
enabling code reusability and the addition of new features to existing code
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog() d.bark() d.speak()
O/P:
dog barking
Animal Speaking

Multilevel Inheritance:
Deriving a new class from old derived class.
This is similar to a relationship representing a child and a grandfather
Syntax:
class A:
#Body of class class B(A):
#Body of class class C(B):
#Body of class

Multiple Inheritance:
When a class is derived from more than one base class it is called multiple Inheritance.
The derived class inherits all the features of the base case

Method Overriding:
When a method in a subclass has the same name, same parameters or signature
and same return type(or sub-type) as a method in its super-class, then the method in the subclass
is said to override the method in the super-class.
Example Method Overriding:
Method Overriding:
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi()); print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());
#O/P:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8

Composition in Python:
In composition one of the classes is composed of one or more instance of other classes.
In other words one class is container and other class is content and if you delete the container
object then all of its contents objects are also deleted.
0 E.g.
class Salary:
def_init_(self, pay):
S1=Salary(100)
self.pay = pay
def get_total(self):
return (self.pay*12)
ans=S1.get_total()
Print(“Total=”ans)
Composition in Python: (Two Classes) {DO it from PPT}
Composition in Python:(Three Classes)
Composition in Python:(Three Classes)

Encapsulation in Python:
 Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP).
 It describes the idea of wrapping data and the methods that work on data within one unit.
 This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data.
 To prevent accidental change, an object‟s variable can only be changed by an object‟s
method.
 Those type of variables are known as private varibale.
 A class is an example of encapsulation as it encapsulates all the data that is member
functions,
 variables, etc.
Protected members:
Protected members (in C++ and JAVA) are those members of the class which cannot be
accessed outside the class but can be accessed from within the class and it‟s subclasses. To
accomplish this in Python, just follow the convention by prefixing the name of the member by a
single underscore “_”.

Private Members:
Private members are similar to protected members, the difference is that the class members
declared private should neither be accessed outside the class nor by any base class. In Python,
there is no existence of Private instance variables that cannot be accessed except inside a class.
However, to define a private member prefix the member name with double underscore “ ”.

What is Data Hiding?


 Data hiding is a concept which underlines the hiding of data or information from the user.
 It is one of the key aspects of Object-Oriented programming strategies.
 It includes object details such as data members, internal work.
 Data hiding is also known as information hiding. In class, if we declare the data members
as
 private so that no other class can access the data members, then it is a process of hiding
data.
Data Hiding example do it from PPT

Advantages of Data Hiding :


 It helps to prevent damage or misuse of volatile data by hiding it from the public.

 The class objects are disconnected from the irrelevant data.


 It isolates objects as the basic concept of OOP.
 It increases the security against hackers that are unable to access important data.

Disadvantages of Data Hiding


 It enables programmers to write lengthy code to hide important data from common
clients.
 The linkage between the visible and invisible data makes the objects work faster, but data
hiding prevents this linkage.

Abstract classes in python:


 An abstract class can be considered as a blueprint for other classes, allows you to create a
 set of methods that must be created within any child classes built from your abstract
class.
 A class which contains one or more abstract methods is called an abstract class.
 An abstract method is a method that has declaration but not has any implementation.
 Abstract classes are not able to instantiated and it needs subclasses to provide
 implementations for those abstract methods which are defined in abstract classes.
 While we are designing large functional units we use an abstract class.
 When we want to provide a common implemented functionality for all implementations
of a component, we use an abstract class.
 Abstract classes allow partially to implement classes when it
 completely implements all methods in a class, then it is called interface.

Why use Abstract Base Classes:


 Abstract classes allow you to provide default functionality for the subclasses.
 Compared to interfaces abstract classes can have an implementation.
 By defining an abstract base class, you can define a common Application Program
Interface(API) for a set of subclasses.
 This capability is especially useful in situations where a third-party is going to provide
implementations, such as with plugins in an application, but can also help you when
working on a large team or with a large code-base where keeping all classes in your head
at the same time is difficult or not possible.

How Abstract Base classes work:


 In python by default, it is not able to provide abstract classes, but python comes up with a
module which provides the base for defining Abstract Base classes(ABC) and that
module name is ABC.
 ABC works by marking methods of the base class as abstract and then registering
concrete classes as implementations of the abstract base.
 A method becomes an abstract by decorated it with a keyword @abstractmethod.

How Abstract Base classes work:


Example: # Python program showing abstract base class work from abc
import ABC, abstractmethod
class Polygon(ABC):
# abstract method def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
# overriding abstract method def noofsides(self):
print("I have 6 sides")
# Driver code R = Triangle() R.noofsides()
R = Pentagon() R.noofsides()
K = Hexagon() K.noofsides()

You might also like