0% found this document useful (0 votes)
14 views22 pages

Module 5 - OOP

1. Object-oriented programming (OOP) is a programming paradigm that organizes code around objects rather than functions. 2. An object can be anything that exists in the real world, like a person, place, or activity, and is characterized by its identity, properties, and behaviors. 3. The basic concepts of OOP include objects, classes, encapsulation, abstraction, data hiding, polymorphism, and inheritance. A class defines common attributes and behaviors of objects, while an object is an instance of a class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views22 pages

Module 5 - OOP

1. Object-oriented programming (OOP) is a programming paradigm that organizes code around objects rather than functions. 2. An object can be anything that exists in the real world, like a person, place, or activity, and is characterized by its identity, properties, and behaviors. 3. The basic concepts of OOP include objects, classes, encapsulation, abstraction, data hiding, polymorphism, and inheritance. A class defines common attributes and behaviors of objects, while an object is an instance of a class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

MODULE – 5

An object-oriented programming (OOP) is a programming language model which is organized


around "objects" rather than "actions" and data rather than logic. Before the introduction of
the Object Oriented Programming paradigm, a program was viewed as a logical procedure that
takes input data, processes it, and produces output. But in case of OOP a problem is viewed in
terms of objects rather than procedure for doing it. Now the question arises what is an object?
An object can be anything that we notice around us. It can be a person (described by name,
address, date of Birth etc, his typing speed), a cup (described by size, color, price etc.), a car
(described by model, color, engine etc., its mileage, speed) and so on. In fact it can be an
identifiable entity. The whole idea behind an object oriented model is to make programming
closer to they real world thereby making it a very natural way of programming. The core of pure
object-oriented programming is to combine into a single unit both data and functions or
methods that operate on that data.
Simula was the first object-oriented programming language. Java, Python, C++, Visual Basic,
.NET and Ruby are the most popular OOP languages today.
Basic Concepts of Object Oriented Programming
The basic concepts related to OOP are as follows:
1. Objects
2. Classes
3. Encapsulation
4. Abstraction
5. Data Hiding
6. Polymorphism
7. Inheritance
OBJECT: -
An object is the basic key concept of Object Oriented Programming. As mentioned before it can
be anything around us - a person, place, any activity or any other identifiable entity. Every
object is characterised by:
Identity: This is the name that identifies an object. For example a Student is the name given to
anybody who is pursuing a course. Or an i-phone is a mobile phone that has been launched by
Apple Inc.
Properties: These are the features or attributes of the object. For example a student will have
his name age, class, date of birth etc. as his attributes or properties. A mobile phone has model,
color, price as its properties.
Behaviour: The behaviour of an object signifies what all functions an object can perform. For
example a student can pass or fail the examination. A mobile phone can click and store
photographs (behave like a camera).
So an object clearly defines an entity in terms of its properties and behaviour. Consider an
example of an object - Windows mobile phone. This phone has certain properties and certain
functions which are different from any other mobile phone- say an Android phone. Both are
mobile phones and so possess common features that every mobile phone should have but yet
they have their own properties and behaviours. The data of a particular object can be accessed
by functions associated with that object only. The functions of one object cannot access the
data of another object.

Prepared by: Mr. R A Khan Page 1


CLASSES
A class is group of objects with same attributes and common behaviours. It is basically a
blueprint to create objects. An object is a basic key concept of OOP but classes provide an
ability to generalize similar type of objects. Both data and functions operating on the data are
bundled as a unit in a class for the same category of objects. Here to explain the term 'same
category of object', let us take the example of mobile phone. A Windows phone, Android phone
and i-phone, all fall into the category of mobile phones. All of these are instances of a class, say
Mobile_phone and are called objects.
Similarly we can have another example where students named Rani and Ravish are objects.
They have properties like name, date of birth, address, class, marks etc. and the behaviour can
be giving examinations. Anybody pursuing any course, giving any type of examination will come
into the category of students. So a student is said to be a class as they share common
properties and behaviours. Although a student can be a school student, a college student or a
university student or a student pursuing a music course and so on, yet all of these have some
properties and behaviours in common which will form a class. An analogy is that you can have
variables of type int which translates to saying that variables that store integers are variables
which are instances (objects) of the int class.

A real instance of a class is called an object and creating the new object is called instantiation.
Objects can also have functionality by using functions that belong to a class. Such functions are
called methods of the class. This terminology is important because it helps us to differentiate
between functions and variables which are independent and those which belong to a class or
object. Collectively, the fields and methods can be referred to as the attributes of that class. Let
us take the example of the class Mobile_phone which is represented in the block diagram
below:

Prepared by: Mr. R A Khan Page 2


Class: Mobile_phone
Data:
Model
Color
Price
Functions:
Store_number()
Missed_calldetail()
Fig 1: Class Mobile_phone
A class is defined before the creation of objects of its type. The objects are then created as
instances of this class as shown in the figure below.
Class: Mobile_phone
Data:
Model
Color
Price

Nokia Lumia Asha i4


Data: Data: Data:
_______________ _______________ _______________
Functions: Functions: Functions:
_______________ _______________ _______________
Fig 2: Class and Objects
In the above example, Nokia Lumia, Asha and i4 are all instances of the class Mobile_phone. All
these instances are similar in the sense that all have basic features that a mobile phone should
have. So all of these are objects of the class Mobile_phone
The general form of class definition in Python and creation of objects will be discussed in the
next chapter.
ENCAPSULATION
Encapsulation is the most basic concept of OOP. It is the combining of data and the functions
associated with that data in a single unit. In most of the languages including python, this unit is
called a class. In Fig -1 showing class Mobile_phone, given under the subtopic Classes, we see
that the name of the class, its properties or attributes and behaviours are all enclosed under
one independent unit. This is encapsulation, implemented through the unit named class.
In simple terms we can say that encapsulation is implemented through classes. In fact the data
members of a class can be accessed through its member functions only. It keeps the data safe
from any external interference and misuse. The only way to access the data is through the
functions of the class. In the example of the class Mobile_phone, the class encapsulates the
data (model, color, price) and the associated functions into a single independent unit.
DATA HIDING

Prepared by: Mr. R A Khan Page 3


Data hiding can be defined as the mechanism of hiding the data of a class from the outside
world or to be precise, from other classes. This is done to protect the data from any accidental
or intentional access.
In most of the object oriented programming languages, encapsulation is implemented through
classes. In a class, data may be made private or public. Private data or function of a class cannot
be accessed from outside the class while public data or functions can be accessed from
anywhere. So data hiding is achieved by making the members of the class private. Access to
private members is restricted and is only available to the member functions of the same class.
However the public part of the object is accessible outside the class.
DATA ABSTRACTION
Do you know the inner details of the monitor of your PC or your mobile phone? What happens
when you switch ON the monitor or when any call is received by you on your phone? Does it
really matter to you what is happening inside these devices? No, it does not. Right? Important
thing for you is whether these devices are working as per your requirement or not? You are
never concerned about their inner circuitry. This is what we call abstraction.
The process of identifying and separating the essential features without including the internal
details is abstraction. Only the essential information is provided to the outside world while the
background details are hidden. Classes use the concept of abstraction. A class encapsulates the
relevant data and functions that operate on data by hiding the complex implementation details
from the user. The user needs to focus on what a class does rather than how it does.
Let us have a look at the Mobile_phone class. The case or body of the mobile phone is
abstraction. This case is the public interface through which the user interacts. Inside the case
there are numerous components such as memory, processor, RAM etc. which are private and
so are hidden behind the public interface called case/body. Thus this case/body is the
abstraction which has separated the essential components from implementation details. So
when you purchase a mobile, you are given information about only the functions and
operations of the mobile. The inside mechanism of the working of the mobile is of no concern
to you. As long as the mobile is functioning properly, you are not bothered about the inner
circuitry of the mobile phone.
Abstraction and Encapsulation are complementary concepts. Through encapsulation only we
are able to enclose the components of the object into a single unit and separate the private and
public members. It is through abstraction that only the essential behaviours of the objects are
made visible to the outside world. So we can say that encapsulation is the way to implement
data abstraction. In another example of class Student, only the essential information like roll
no, name, date of birth, course etc. of the student are visible. The secret information like
calculation of grades, allotment of examiners etc. is hidden.
INHERITANCE
Inheritance is one of the most useful characteristic of object-oriented programming as it
enforces reusability of code. Inheritance is the process of forming a new class (derived class)
from an existing class (called the base class). The data members and the methods associated
with the data are accessible in the inherited class.
Let us understand this characteristic with the help of the class Mobile_phone.
An i-phone is a class in itself. It is a type of mobile phone. So we can have Mobile_phone as the
base class and i_phone as its derived class as shown in the figure below:

Prepared by: Mr. R A Khan Page 4


Class: Mobile_phone
Data:
Model
Color
Price

Window Phone Android Phone i-Phone


Data: Data: Data:
_______________ _______________ _______________
Functions: Functions: Functions:
_______________ _______________ _______________
Fig 3: Inheritance
Such hierarchical classification helps to obtain a new class from an existing class. The derived
class can also contain some new attributes of itself. So the derived class contains features of the
base class as well as of itself. For example, an i-phone will have all the features of a
Mobile_phone class in addition to its own characteristics. Such a relationship between the two
classes is known as "a kind of "relationship. For example an i-phone is a kind of mobile phone.
So we see that the base class can be reused again and again to define new classes. Another
advantage of inheritance is its transitive nature. If a class i_phone inherits properties of another
class Mobile_phone, then all derived classes of i_phone will inherit properties of the class
Mobile_phone. All these factors make inheritance a very important characteristic of object
oriented programming.
POLYMORPHISM
The word Polymorphism is formed from two words - poly and morph where poly means many
and morph means forms. So polymorphism is the ability to use an operator or function in
various forms. That is a single function or an operator behaves differently depending upon the
data provided to them. Polymorphism can be achieved in two ways:
1. Operator Overloading
In class XI you have worked with '+ 'operator. You must have noticed that the '+' operator
behaves differently with different data types. With integers it adds the two numbers and with
strings it concatenates or joins two strings.
For example: Print 8+9 will give 17
and Print "Python" + "programming" will give the output as Pythonprogramming.
This feature where an operator can be used in different forms is known as Operator
Overloading and is one of the methods to implement polymorphism.
2. Function Overloading
Polymorphism in case of functions is a bit different. A named function can also vary depending
on the parameters it is given. For example, we define multiple functions with same name but
different argument list as shown below:
def test(): #function 1
print "hello"
def test(a, b): #function 2

Prepared by: Mr. R A Khan Page 5


return a+b
def test(a, b, c): #function 3
return a+b+c
In the example above, three functions by the same name have been defined but with different
number of arguments. Now if we give a function call with no argument, say test(), function 1
will be called. The statement test(10,20) will lead to the execution of function 2 and if the
statement test(10,20,30) is given Function 3 will be called. In either case, all the functions
would be known in the program by the same name. This is another way to implement
polymorphism and is known as Function Overloading.
As we see in the examples above, the function called will depend on the argument list - data
types and number of arguments. These two i.e. data types and the number of arguments
together form the function signature. Please note that the return types of the function are no
where responsible for function overloading and that is why they are not part of function
signature.
Here it must be taken into consideration that Python does not support function overloading as
shown above although languages like Java and C/C++ do. If you run the code of three test
functions, the second test() definition will overwrite the first one. Subsequently the third test()
definition will overwrite the second one. That means if you give the function call test(20,20) , it
will flash an error stating, "Type Error: add() takes exactly 3 arguments (2 given)". This is
because, Python understands the latest definition of the function test() which takes three
arguments.
STATIC AND DYNAMIC BINDING
Binding is the process of linking the function call to the function definition. The body of the
function is executed when the function call is made. Binding can be of two types:
Static Binding: In this type of binding, the linking of function call to the function definition is
done during compilation of the program.
Dynamic Binding: In this type of binding, linking of a function call to the function definition is
done at run time. That means the code of the function that is to be linked with function call is
unknown until it is executed. Dynamic binding of functions makes the programs more flexible.
ADVANTAGES OF OOP
Object Oriented programming has following advantages:
Simplicity: The objects in case of OOP are close to the real world objects, so the complexity of
the program is reduced making the program structure very clear and simple. For example by
looking at the class Mobile_phone, you can simply identify with the properties and behaviour of
an actual mobile phone. This makes the class Mobile_phone very simple and easy to
understand.
Modifiability: It is easy to make minor changes in the data representation or the procedures in
an OO program. Changes inside a class do not affect any other part of a program, since the only
public interface that the external world has to a class is through the use of methods.
Extensibility and Maintainability: It is quite easy to add new features and extend the program
in case of object oriented programming. It can be simply done by introducing a few new objects
and modifying some existing ones. The original base class need not be modified at all. Even
objects can be maintained separately. There by making locating and fixing problems easier. For
example if a new version of i-phone is introduced, a new derived class of the class i_phone for

Prepared by: Mr. R A Khan Page 6


the new version may be created and no other class in the class hierarchy need to be modified.
Similarly if any behaviour of a Windows phone changes, maintenance has to be done only for
the class Windows phone.
Re-usability: Objects can be reused in different programs. The class definitions can be reused in
various applications. Inheritance makes it possible to define subclasses of data objects that
share some or all of the main class characteristics. It forces a more thorough data analysis,
reduces development time, and ensures more accurate coding.
Security: Since a class defines only the data it needs to be concerned with, when an instance of
that class (an object) is run, the code will not be able to accidentally access other program data.
This characteristic of data hiding provides greater system security and avoids unintended data
corruption.
DIFFERENCE BETWEEN PROCEDURE-ORIENTED AND OBJECT-ORIENTED PROGRAMMING
Procedure-Oriented Programming Object-Oriented Programming
In POP, program is divided into small parts In OOP, program is divided into parts called
called functions objects.
In POP, Importance is not given to data but In OOP, Importance is given to the data rather
to functions as well as sequence of actions than procedures or functions because it works
to be done. as a real world.
POP follows Top Down approach. OOP follows Bottom Up approach.
POP does not have any access specifier. OOP has access specifiers named Public, Private,
Protected, etc.
In POP, Data can move freely from function In OOP, objects can move and communicate
to function in the system. with each other through member functions.
To add new data and function in POP is not OOP provides an easy way to add new data and
so easy. function.
In POP, Most function uses Global data for In OOP, data can not move easily from function
sharing that can be accessed freely from to function,it can be kept public or private so we
function to function in the system. can control the access of data.
POP does not have any proper way for OOP provides Data Hiding so provides more
hiding data so it is less secure. security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overloading.
Example of POP are: C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET,C#.NET,
Python
DIFFERENCE BETWEEN CLASS AND OBJECT
Class Object
Class is the blueprint of an object. It is used to Object is an instance of class
declare and create objects
No memory is allocated when a class is declared Memory is allocated as soon as an object
is creted
A class is a group of similar objects Object is a real world entity such as book
car etc
Class is a logical entity Object is a physical entity

Prepared by: Mr. R A Khan Page 7


Class can only be declared once. Object can be created many times as per
requirement.
Example of class can be Car Objects of the class can be Maruti
Mercedes, BMW etc
Python OOPs Concepts
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects
and classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind
the data and the functions that work on that together as a single unit so that no other part of
the code can access this data.
OOPs Concepts in Python
 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction
Python OOPs Concepts

Python Class
A class is a collection of objects. A class contains the blueprints or the prototype from which the
objects are being created. It is a logical entity that contains some attributes and methods.

Prepared by: Mr. R A Khan Page 8


To understand the need for creating a class let’s consider an example, let’s say you wanted to
track the number of dogs that may have different attributes like breed, and age. If a list is used,
the first element could be the dog’s breed while the second element could represent its age.
Let’s suppose there are 100 different dogs, then how would you know which element is
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it’s the exact need for classes.
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N

Creating an Empty Class in Python


In the above example, we have created a class named Dog using the class keyword.

# Python3 program to
# demonstrate defining
# a class

class Dog:
pass

# Python program to
# demonstrate defining
# a class

class Dog:
pass

Python Objects
The object is an entity that has a state and behavior associated with it. It may be any real-world
object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers,
even arrays, and dictionaries, are all objects. More specifically, any single integer or any single
string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an
object that can hold other objects, and so on. You’ve been using objects all along and may not
even realize it.
An object consists of:

Prepared by: Mr. R A Khan Page 9


 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the state, behavior, and identity let us take the example of the class dog
(explained above).
 The identity can be considered as the name of the dog.
 State or Attributes can be considered as the breed, age, or color of the dog.
 The behavior can be considered as to whether the dog is eating or sleeping.
Creating an Object
This will create an object named obj of the class Dog defined above. Before diving deep into
objects and classes let us understand some basic keywords that will we used while working with
objects and classes.

obj = Dog()

The Python self


1. Class methods must have an extra first parameter in the method definition. We do not give
a value for this parameter when we call the method, Python provides it
2. If we have a method that takes no arguments, then we still have to have one argument.
3. 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) – this is all the special self is
about.
The Python __init__ Method
The __init__ Method is similar to constructors in C++ and Java. It is run 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. Now let us define a class and create some objects using the self and __init__ method.
Creating a class and object with class and instance attributes

class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
self.name = name

# Driver code
# Object instantiation

Prepared by: Mr. R A Khan Page 10


Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class attributes


print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes


print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))

Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Creating Classes and objects with methods
Here, The Dog class is defined with two attributes:
 attr1 is a class attribute set to the value “mammal”. Class attributes are shared by all
instances of the class.
 __init__ is a special method (constructor) that initializes an instance of the Dog class. It
takes two parameters: self (referring to the instance being created) and name (representing
the name of the dog). The name parameter is used to assign a name attribute to each
instance of Dog.
The speak method is defined within the Dog class. This method prints a string that includes
the name of the dog instance.
The driver code starts by creating two instances of the Dog class: Rodger and Tommy. The
__init__ method is called for each instance to initialize their name attributes with the provided
names. The speak method is called in both instances (Rodger.speak() and Tommy.speak()),
causing each dog to print a statement with its name.

class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
self.name = name

def speak(self):
print("My name is {}".format(self.name))

Prepared by: Mr. R A Khan Page 11


# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class methods


Rodger.speak()
Tommy.speak()

Output
My name is Rodger
My name is Tommy
Python Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class.
The class that derives properties is called the derived class or child class and the class from
which the properties are being derived is called the base class or parent class. The benefits of
inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then all
the subclasses of B would automatically inherit from class A.
Types of Inheritance
 Single Inheritance: Single-level inheritance enables a derived class to inherit characteristics
from a single-parent class.
 Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit properties
from an immediate parent class which in turn inherits properties from his parent class.
 Hierarchical Inheritance: Hierarchical-level inheritance enables more than one derived
class to inherit properties from a parent class.
 Multiple Inheritances: Multiple-level inheritance enables one derived class to inherit
properties from more than one base class.
Inheritance in Python
In the above article, we have created two classes i.e. Person (parent class) and Employee (Child
Class). The Employee class inherits from the Person class. We can use the methods of the
person class through the employee class as seen in the display function in the above code. A
child class can also modify the behavior of the parent class as seen through the details()
method.

# Python code to demonstrate how parent constructors


# are called.

Prepared by: Mr. R A Khan Page 12


# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))

# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using


# its instance
a.display()
a.details()

Output
Rahul
886012
My name is Rahul

Prepared by: Mr. R A Khan Page 13


IdNumber: 886012
Post: Intern
Python Polymorphism
Polymorphism simply means having many forms. For example, we need to determine if the
given species of birds fly or not, using polymorphism we can do this using a single function.
Polymorphism in Python
This code demonstrates the concept of inheritance and method overriding in Python classes. It
shows how subclasses can override methods defined in their parent class to provide specific
behavior while still inheriting other methods from the parent class.

class Bird:

def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

Output
There are many types of birds.
Most of the birds can fly but some cannot.

Prepared by: Mr. R A Khan Page 14


There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Python Encapsulation
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 types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.

Encapsulation in Python
In the above example, we have created the c variable as the private attribute. We cannot even
access this attribute directly and can’t even change its value.

# Python program to
# demonstrate private members

# Creating a Base class


class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

Prepared by: Mr. R A Khan Page 15


# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

Output
GeeksforGeeks

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 types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc. The goal of information hiding is to ensure that an object’s state is always valid
by controlling access to attributes that are hidden from the outside world.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section
handles all the sales-related activities and keeps records of all the sales. Now there may arise a
situation when due to some reason an official from the finance section needs all the data about
sales in a particular month. In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales section and then request
him to give the particular data. This is what encapsulation is. Here the data of the sales section
and the employees that can manipulate them are wrapped under a single name “sales section”.
Using encapsulation also hides the data. In this example, the data of the sections like sales,
finance, or accounts are hidden from any other section.
Protected members
Protected members (in C++ and JAVA) are those members of the class that cannot be accessed
outside the class but can be accessed from within the class and its subclasses. To accomplish
this in Python, just follow the convention by prefixing the name of the member by a single
underscore “_”.
Although the protected variable can be accessed out of the class as well as in the derived class
(modified too in derived class), it is customary(convention not a rule) to not access the
protected out the class body.

Prepared by: Mr. R A Khan Page 16


Note: The __init__ method is a constructor and runs as soon as an object of a class is
instantiated.

# Python program to
# demonstrate protected members

# Creating a base class


class Base:
def __init__(self):

# Protected member
self._a = 2

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)

# Modify the protected variable:


self._a = 3
print("Calling modified protected member outside class: ",
self._a)

obj1 = Derived()

obj2 = Base()

# Calling protected member


# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside


print("Accessing protected member of obj2: ", obj2._a)

Output:
Calling protected member of base class: 2
Calling modified protected member outside class: 3
Accessing protected member of obj1: 3
Accessing protected member of obj2: 2

Prepared by: Mr. R A Khan Page 17


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 “__”.
Note: Python’s private and protected members can be accessed outside the class
through python name mangling.

# Python program to
# demonstrate private members

# Creating a Base class

class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AttributeError as
# private member of base class
# is called inside derived class

Output:
GeeksforGeeks

Prepared by: Mr. R A Khan Page 18


Traceback (most recent call last):
File "/home/f4905b43bfcf29567e360c709d3c52bd.py", line 25, in <module>
print(obj1.c)
AttributeError: 'Base' object has no attribute 'c'

Traceback (most recent call last):


File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27, in <module>
obj2 = Derived()
File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20, in __init__
print(self.__c)
AttributeError: 'Derived' object has no attribute '_Derived__c'

Data Abstraction
It hides unnecessary code details from the user. Also, when we do not want to give out
sensitive parts of our code implementation and this is where data abstraction came.
Data Abstraction in Python can be achieved by creating abstract classes.

Data hiding
In Python, we use double underscore (Or __) before the attributes name and those
attributes will not be directly visible outside.
Python

class MyClass:

# Hidden member of MyClass


__hiddenVariable = 0

# A member method that changes


# __hiddenVariable
def add(self, increment):
self.__hiddenVariable += increment
print (self.__hiddenVariable)

# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)

# This line causes error


print (myObject.__hiddenVariable)

Output :
2
7

Prepared by: Mr. R A Khan Page 19


Traceback (most recent call last):
File "filename.py", line 13, in
print (myObject.__hiddenVariable)
AttributeError: MyClass instance has
no attribute '__hiddenVariable'
In the above program, we tried to access a hidden variable outside the class using an o bject
and it threw an exception.
We can access the value of a hidden attribute by a tricky syntax:
Python

# A Python program to demonstrate that hidden


# members can be accessed outside a class
class MyClass:

# Hidden member of MyClass


__hiddenVariable = 10

# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)

Output :
10
Private methods are accessible outside their class, just not easily accessible. Nothing in
Python is truly private; internally, the names of private methods and attributes are mangled
and unmangled on the fly to make them seem inaccessible by their given names [See this for
source ].
Printing Objects
Printing objects give us information about objects we are working with. In C++, we can do
this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the
class. In Java, we use toString() method.
In python, this can be achieved by using __repr__ or __str__ methods.
Python

class Test:
def __init__(self, a, b):
self.a = a
self.b = b

def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)

def __str__(self):

Prepared by: Mr. R A Khan Page 20


return "From str method of Test: a is %s," \
"b is %s" % (self.a, self.b)

# Driver Code
t = Test(1234, 5678)
print(t) # This calls __str__()
print([t]) # This calls __repr__()

Output :
From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]
Important Points about Printing:
If no __str__ method is defined, print t (or print str(t)) uses __repr__.
Python

class Test:
def __init__(self, a, b):
self.a = a
self.b = b

def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)

# Driver Code
t = Test(1234, 5678)
print(t)

Output :
Test a:1234 b:5678
If no __repr__ method is defined then the default is used.
Python

class Test:
def __init__(self, a, b):
self.a = a
self.b = b

# Driver Code
t = Test(1234, 5678)
print(t)

Output :
<__main__.Test instance at 0x7fa079da6710>

Prepared by: Mr. R A Khan Page 21


EXCERCISE
1. What is Object Oriented Programming? List some of its advantages.
2. Differentiate between an object and a class.
3. What is inheritance? Explain with an example.
4. List its three features that make it an important characteristic of OOP.
5. Consider the figure given below and answer the questions that follow:
STUDENT ⇒GRADUATE ⇒POST GRADUATE
a. Name the base class and the derived class.
b. Which concept of OOP is implemented in the figure given above?
6. How do abstraction and encapsulation complement each other?
7. Explain polymorphism with an example.
8. Explain Data Hiding with respect to OOP.
9. Explain Function overloading with an example.
10. Is function overloading supported by Python? Give reasons.
11. Write the overloaded function definitions of add()- on adds two numbers and other
concatenates two strings.
12. Predict the output of the following program. Also state which concept of OOP is being
implemented?
def sum(x,y,z):
print "sum= ", x+y+z
def sum(a,b):
print "sum= ", a+b
sum(10,20)
sum(10,20,30)
13. State whether the following are function overloading or not. Explain why or why not.
a. def (a,b):
def(x,y) :
b. def(x,y,z)
def(e,f)
14. Define binding.
15. Differentiate between static and dynamic binding.
16. Write a program to find area of following using function overloading.
17. Area of circle (function with one parameter)
18. Area of rectangle (function with two parameters)
19. Area of triangle (function with three parameters)
20. Write a program to find out volume of the following using function overloading.
 volume of cube
 volume of cuboid
 volume of cylinder

Prepared by: Mr. R A Khan Page 22

You might also like