0% found this document useful (0 votes)
15 views

MT

Uploaded by

Ashish Ranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

MT

Uploaded by

Ashish Ranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 184

Object Oriented

Programming
Dr. Bharat Singh
PhD, CSE
History
History
• Object-oriented programming (OOP) is a programming paradigm that
has revolutionized the way software is developed.
• OOP traces its roots back to the 1960s when computer scientists
began to explore new ways of organizing and structuring code.
• The concept of objects, which encapsulate data and behavior, was
introduced to improve software development processes.
• One of the earliest programming languages that embraced OOP
principles was Simula, developed in the 1960s by Ole-Johan Dahl and
Kristen Nygaard. Simula introduced the concept of classes and
objects, laying the foundation for modern OOP languages.
• OOP is a fundamental concept in many programming languages,
including Python, Ruby, and C#.
History
Software Evolution 5

Layers of Computer software


6

Software Evolution (Conti..)


• By, Ernest Tello (a well known writer in field of Artificial intelligence) Software
evolution has had distinct phases or “layers” of growth like a Tree.

• These layers are built up one by one over the last five decades.

• However, the each layer is improvement over the previous one, BUT each of the
layers continues to be functional NOT like tree where only the uppermost layer
is functional.
7

Software Evolution (Conti..)


• By, Alan Kay one of the promoter of object-oriented paradigm said, “As
complexity increases, architecture dominates the basic material”.

• To build today’s complex software system, it is just not enough to put together a
sequence of programming statements and set of procedures and modules.

• We need to incorporate sound construction techniques and program structures that


are easy to comprehend, implement and modify.
8

Software Evolution (Conti..)


• Since the invention of the computer many programming approaches have been
tried. These include techniques such as, modular programming, top-down,
bottom-up programming.

• With the advent of language such as C, structured programming become very


popular and was main technique in 1980s. It can moderately handle complex
programs very easily.

• However, when the program grew larger even structured programming approach
failed to show desired results in terms of bug-free results, easy-to-maintain and
reusable programs.
10

Software Evolution (Conti..)


• Object-oriented programming (OOP) is an approach to program organization
and development that attempts to eliminate some pitfalls of conventional
programming techniques.

• It is a new way to organize and develop programs and has nothing to do with
any particular language.
What is programming?
11

A program is simply a sequence of commands instructing a


computer what to do.
Programming is taking
A problem
Find the area of a rectangle
A set of data
length
width
A set of functions
area = length * width
Then,
Applying functions to data to solve the problem
• The degrees of freedom available in devising this list,
make programs potentially the most complex and
intricate entities
• ever envisioned by humans.Many people believe that
OOP is a product of the 1980s and the work done by
Bjarne Stroustrup in moving the C language into the
object-oriented world by creating the C++ language.
History
Programming concept Evolution/ Programming
Paradigm
• Paradigm can also be termed as a method to solve some
problems or do some tasks.
• A programming paradigm is an approach to solve the problem
using some programming language or also we can say it is a
method to solve a problem using tools and techniques that are
available to us
Programming Paradigm
Procedural Programming
• Procedural Programming can be defined as a programming model
which is derived from structured programming, based upon the
concept of calling procedure.
• Procedures, also known as routines, subroutines or functions, simply
consist of a series of computational steps to be carried out.
• During a program’s execution, any given procedure might be called at
any point, including by other procedures or itself.
• FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.
Procedural Programming
• It is a series of computational steps
are divided modules which means def Sum(sample_list):
that the code is grouped in functions total = 0
and the code is serially executed step for x in sample_list:
total += x
by step so basically, return total
list1 = [10, 200, 50, 70]
• it combines the serial code to instruct list2 = [3, 26, 33, 13]
a computer with each step to perform print(Sum(list1))
a certain task. print(Sum(list2))

• This paradigm helps in the modularity


of code and modularization is usually
done by the functional
implementation.
A Look at Procedural-Oriented
19

Programming

The main program coordinates calls to procedures and hands over


appropriate data as parameters.
A Look at Procedural-Oriented
20

Programming (Conti..)

Relationship of data and functions on procedural programming


Procedural Concept
21

• Procedural Languages
• C, Pascal, Basic, Fortran
• Facilities to
• Pass arguments to functions
• Return values from functions

• For the rectangle problem, we develop a function


int compute_area (int l, int w){
return ( l * w );
}
A Look at Procedural-Oriented 22

Programming (Conti..)
• Some characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing thins (Algorithms)
• Large programs are divided into smaller programs know as functions.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach of program design.

• Main Drawbacks:
• Very little attention given to the data that are being used by various functions. In a large program it is
difficult to identify what data is used by which function.
• Global data are more vulnerable to an inadvertent change by a function.
• It does not model real world problems very well. This is because functions are action-oriented and do not
really correspond to the elements of the problem.
Procedural Programming
• Advantages
• General-purpose programming
• Code reusability
• Portable source code
• It is easy to trace the flow of the program
• Disadvantages
• Data protection
• Not suitable for real-world objects
Object Oriented Programming
• Object-oriented programming can be defined as a programming
model which is based upon the concept of objects.
• An object has two characteristics:-
• attributes
• behaviors
• For example, an object could represent an employee with attributes
such as name, title, experience, etc., with behaviors like working, on-
leave, underperformed.
• Objects contain data in the form of attributes/properties and code in
the form of methods/behaviours.
Object Oriented Programming
• In object-oriented programming, computer programs are designed
using the concept of objects that interact with the real world.
• Object-oriented programming languages are various but the most
popular ones are class-based, meaning that objects are instances of
classes, which also determine their types.
• Many of the most widely used programming languages (such as C++,
Java, and Python)
• Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart,
Swift, Scala.
Object Oriented Programming
• Advantages:-
class animal:
• It can relate to real-world entities. species = "bird"
def__init__(self, name, age):
• Code Reusability self.name = name
• Data hiding self.age = age

parrot = animal("parrot", 10)


sparrow = animal("sparrow", 15)
• Disadvantages:- print("parrot is a {}".format(parrot.__class__.species))
• Complex Design print("sparrow is also a {}".format(sparrow.__class__.species))

• Large size print("{} is {} years old".format( parrot.name, parrot.age))


print("{} is {} years old".format( sparrow.name, sparrow.age))
• Slow Speed
Object-Oriented Programming 27

Paradigm

Organization of data and functions in OOP

11/28/2024
Object-Oriented Concept 28

Objects of the program interact by sending messages to each other

11/28/2024
Object-Oriented Concept (Conti..) 29

• Major motivating factor in the invention of Object-oriented approach is to remove some flaws encountered in the
procedural programming languages.
• OOP treats data as a critical element in the program development and does not allow it to flow freely around the
system.
• It ties data closely to the functions which operate on it, and protect it from accidental modification from outside
functions.
• OOP decompose the problem in smaller entities called as objects, and build data and functions around it.
• It provides the basic concepts of:
• Objects
• Classes
• Data Abstraction
• Data Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Objects 30

An object is an encapsulation of both functions and data


• Objects are an Abstraction
• represent real world entities
• Classes are data types that define shared common properties or attributes
• Objects are instances of a class
• Objects have State
• have a value at a particular time
• Objects have Operations
• associated set of operations called methods that describe how to carry out operations
• Objects have Messages
• request an object to carry out one of its operations by sending it a message
• messages are the means by which we exchange data between objects

11/28/2024
Objects 31

An object is an encapsulation of both functions and data

Two ways of representing an Object

11/28/2024
32

OO Perspective

Let's look at the Rectangle through object oriented way:

• Define a new type Rectangle (a class)


• Data
• width, length
• Function
• area()
• Create an instance of the class (an object)
• Request the object for its area

In C++, rather than writing a procedure, we define a class that encapsulates the knowledge
necessary to answer the question - here, what is the area of the rectangle.
11/28/2024
Example Object Oriented Code
33

class Rectangle int area()


{ {
private: return width*length;
}
int width, length; };
public:
Rectangle(int w, int l) main()
{ {
Rectangle rect(3, 5);
width = w; cout << rect.area()<<endl;
length = l; }
}
11/28/2024
Functional Programming
• Functional programming paradigms is a paradigm in which everything
is bind in pure mathematical functions style.
• It is known as declarative paradigms because it uses declarations
statements.
• It uses the mathematical function and treats every statement as
functional expression as an expression is executed to produce a value.
• The paradigms mainly focus on “what to solve” rather than “how to
solve”.
Functional Programming
• Advantages # Functional way of finding sum of a list
import functools
• Simple to understand
• implementing concurrency becomes efficient mylist =[11, 22, 33, 44]
• Making debugging and testing easierby using # Recursive Functional approach
def sum_the_list(mylist):
immutable values
if len(mylist) ==1:
• Enhances the comprehension and readability return mylist[0]
else:
of the code return mylist[0]
+sum_the_list(mylist[1:])
# lambda function is used
print(functools.reduce(lambdax, y: x +y, mylist))
• Disadvantages
• Low performance
• Writing programs is a daunting task
• Low readability of the code
Procedural programming Vs Object-oriented
programming
• Procedural programming is used • Object-oriented programming is
for designing medium-sized used for designing large and
programs. complex programs.
• In procedural programming, the • In object-oriented programming,
function is more important than data is more important than
the data. function.
Object-Oriented Programming
• OOP – Object-Oriented Programming Principle is the strategy or style
of developing applications based on objects.
• Anything in the world can be defined as an object.
• And in the OOPs, it can be defined in terms of its properties and
behavior.
Why OOPs are Popular in Comparison to Other
Types of Programming Principles?

• Object-Oriented Programming Principles is the most popular amongst


others because it relates to real-life objects.

• Every operation that is going to be functional is considered in terms


of classes and objects.
Object Oriented Paradigm
• OOP:
• Treats data as critical element in program development.
• Does not allow it to flow freely in the system.
• Ties data closely to the functions that operate on it.
• Protects data from unintentional modification by other functions.
• Allows to decompose problem into number of entities called objects.
1.2 Object Oriented Paradigm

Object-oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area of both
data and functions that can be used as templates for creating copies of such modules on demand
1.2 Object Oriented Paradigm
• Features:
1. Emphasis on data than procedure
2. Programs are divided into what is known as objects
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together in data
structure.
5. Data is hidden and cannot be access by external functions.
6. Objects may communicate with each other through methods
7. New data and methods can be added whenever necessary.
8. Follows bottom up approach in program design.
• Object-oriented programming is an approach that provides a way of
modularizing programs by creating partitioned memory area for both
data and functions that can be used as a templates for creating copies
of such modules on demand.
1.3 Basic Concepts of Object Oriented
Programming
• Object and Classes
• Data abstraction and Encapsulation
• Inheritance
• Polymorphism
• Compile Time and Runtime Mechanisms
• Dynamic binding
• Message Communication
1.3 Basic Concepts of Object-Oriented
Programming
Object and Classes
• Basic runtime entities in an object-oriented system.
• Can be any item that program has to handle or can also be user
defined data types such as vectors or lists.
• In OOP, programming is all about objects and nature of
communication between them.
• Objects chosen must be close to real-world objects.
• When a program is executed, the objects interact by sending
messages to one another.
1.3 Basic Concepts of Object-Oriented
Programming
Objects and Classes
• Each object contains the data and code to manipulate data.
• Objects can interact without knowing the details of each other’s data
or code.

Representation of an object in
object-oriented analysis and design
1.3 Basic Concepts of Object-Oriented
Programming
Objects and Classes
• Data and code of an object can be made user-defined data type using
the concept of a class.
• Class can be thought of as a ‘data type’ and an object as a variable of
that data type.
• Once a class has been defined we can create any number of objects
for that class.
• Each object is associated with the data type class with which they are
created.
• Basically a class is a collection of objects of similar type.
Classes

• A class is nothing but a blueprint for creating different objects which


defines its properties and behaviors.
• An object exhibits the properties and behaviors defined by its class.
• A class can contain fields and methods to describe the behavior of an
object.
• Methods are nothing but members of a class that provide a service
for an object or perform some business logic.
Objects

• An object is an instance of a class created using a new operator. The


new operator returns a reference to a new instance of a class.
1.3 Basic Concepts of Object-Oriented
Programming
Data Abstraction and Encapsulation
• Abstraction is wrapping up of data and methods into single unit called
class.
• Data is not available to the outside world.
• Only those methods, which are wrapped in a class can access it.
• Methods provide interface between object’s data and the program.
• Insulation of the data from direct access of the program is called data
hiding.
• Data Abstraction and Encapsulation
• Encapsulation allows for the hiding of internal details and provides a
public interface for interacting with an object.
• This helps to ensure data integrity and prevents unauthorized access
or modification of an object’s internal state.
• By encapsulating data and methods into objects, code can be reused
in different parts of an application or even in different applications
altogether. This reduces code duplication and makes it easier to
maintain and update code.
1.3 Basic Concepts of Object-Oriented
Programming
Inheritance
1.3 Basic Concepts of Object-Oriented
Programming
• Process by which objects of one class acquire the properties of
objects of another class.
• Supports the concept of hierarchical classification.
• Provides the idea of reusability.
• We can add additional features to an existing class modifying it.
• A new class can be created from the existing one such that it has
combined features of both the classes.
• The derived class is known as subclass.
• Without the use of inheritance each will have to explicitly include all
of its features.
Inheritance
•Inheritance is the process by which objects of one class can get the properties of objects of
another class.

• Inheritance means one class of objects inherits the data and behaviors from another class.
Inheritance maintains the hierarchical classification in which a class inherits from its parents.

•Inheritance provides the important feature of OOP that is reusability. That means we can
include additional characteristics to an existing class without modification. This is possible
deriving a new class from existing one.

• Inheritance is a relationship between classes where one class is the parent class of another
(derived) class.
•The derived class holds the properties and behaviour of base class in addition to the
properties and behaviour of derived class.
• Inheritance allows for the creation of new classes based on existing
classes.
• This promotes code reusability by allowing a new class to inherit the
properties and behaviors of an existing class.
• This reduces code duplication and makes it easier to manage and
maintain large codebases.
1.3 Basic Concepts of Object-Oriented
Programming
Polymorphism
1.3 Basic Concepts of Object-Oriented
Programming
• Polymorphism means the ability to take more than one form.
• A single function name can be used to handle different number and
different types of arguments.
• Allows objects having different internal structures to share the same
external interface.
• General class of operations may be accessed in the same manner
even though specific actions associated with each operation may
differ.
• Extensively used in implementing inheritance.
Polymorphism

• (Poly means “many” and morph means “form”).


• Polymorphism means the ability to take more than one form.
• Polymorphism plays a main role in allocate objects having different
internal structures to share the same external interface
Data Abstraction

• Data abstraction refers to the act of representing important


description without including the background details or explanations.
• They summarize all the important properties of the objects that are
to be created.
• Classes use the concepts of data abstraction and it is called as
Abstract Data Type (ADT)
1.3 Basic Concepts of Object-Oriented
Programming
Dynamic Binding

• Linking of a procedure call to the code to be executed in response to the call.


• Code associated with a procedure call is not known until the time of call at
runtime
• It is associated with polymorphism and inheritance
• A procedure call associated with polymorphic reference depends on the
dynamic type of that reference.
Data Encapsulation

• Data Encapsulation means wrapping of data and functions into a


single unit (i.e. class).
• It is most useful feature of class. The data is not easy to get to the
outside world and only those functions which are enclosed in the
class can access it.
• These functions provide the boundary between Object’s data and
program.
• This insulation of data from direct access by the program is called as
Data hiding.
1.3 Basic Concepts of Object-Oriented
Programming
Message Communication
•In object – oriented program a set of objects
communicate with each other.
•Process of programming in OOP involves:
•Creating classes that define objects and
their behavior.
•Creating objects from class definitions.
•Establishing communication among
objects
1.3 Basic Concepts of Object-Oriented
Programming
Objects communicate with one another the same way as people may
pass messages to one another.

•Message is a request for execution of procedure.


•Message invokes a method in receiving object.
•Desired result is generated.

Objects have a life cycle . They can be created and destroyed.


Communication with an object is feasible as long as it is alive.
1.4 Benefits of OOP
• Can eliminate redundant code and extend the use of existing classes.
• Saves development time and assures higher productivity.
• Programmers can build secure programs that cannot be invaded by
code in other parts of the program.
• Multiple objects can coexist without any interference.
• Easy to partition work in a project based on objects.
• Data - centered design captures more details of a model.
• OO systems can be easily upgraded from small to large systems.
• Software complexity can be easily managed.
1.5 Applications of OOP
• OOP can simplify complex problems.
• Promising areas for application of OOP include:
• Real-time systems
• Simulation and modelling
• Object-oriented databases
• Hypertext and hypermedia
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM (Computer-integrated Manufacturing) /CAD/CAD (Computer-Aided
Design & Manufacture system)
Java Introction
• A list of object-oriented languages in existence , but this examination of their
history would not be complete without reference to Java.
• Delivered by Sun Microsystems in 1995, its original objective was to let
devices, peripherals and appliances possess a common programming
interface.
• However, the tremendous upsurge in browsing the Internet enabled its
machine independence to be utilised in facilitating far more functionality to
be offered by web sites through Java applets.
• A Java compiler outputs a pseudo-code which must be executed on any
computer having an appropriate interpreter known as a Java virtual machine.
• With a similar syntax and many improvements to C++, like garbage collection,
its deployment has been extremely rapid (Harold 1998).
• A recent survey reveals that over 40% of US businesses asked are already
using it and over 30% intend to soon (Andrews 1998).
Packages
• A Package can be defined as a grouping of related types (classes and
interfaces) providing access protection and name space
management.
• A package is a directory that contains a group of related classes and
interfaces. Java

Packages

Classes and Interfaces

Methods
Benefits of OOP in Modern Development
• OOP provides several benefits in modern software development:
• Code reusability
• Maintainability
• Scalability
• Flexibility
• Modularity
Benefits of OOP in Modern Development
• OOP provides several benefits in modern software development:
• Code reusability: OOP allows for the creation of reusable code
components, which can be used in different parts of an application or
even in different applications altogether. This reduces code
duplication and makes it easier to maintain and update code.

• Maintainability: OOP promotes code modularity, which makes it


easier to understand, update, and debug code. Changes made to one
part of the codebase are less likely to affect other parts, reducing the
risk of introducing bugs or breaking existing functionality.
Benefits of OOP in Modern Development
• Scalability: OOP allows for the creation of scalable systems by breaking them
down into smaller, more manageable objects. This makes it easier to add new
features or modify existing ones without affecting the entire system.

• Flexibility: OOP provides a flexible and adaptable approach to software


development. The use of interfaces and polymorphism allows for the creation
of code that can work with different types of objects, making it easier to
extend or modify the system as requirements change.

• Modularity: OOP promotes code modularity, which makes it easier to


organize and manage large codebases. By breaking down a system into
smaller, self-contained objects, it becomes easier to understand, test, and
maintain the code.
OOP in Popular Programming Languages
• Significant object-oriented languages include Ada,
ActionScript, C++, Common Lisp, C#, Dart, Eiffel,
Fortran 2003, Haxe, Java, JavaScript, Kotlin, Logo,
MATLAB, Objective-C, Object Pascal, Perl, PHP, Python,
R, Raku, Ruby, Scala, SIMSCRIPT, Simula, Smalltalk,
Swift, Vala and Visual Basic.NET.
• OOP is widely used in many popular programming
languages, including Java, Python, and C++.
• Each language has its own syntax and features for
implementing OOP principles.
Thank You!
Object Oriented
Programming
Dr. Bharat Singh
PhD, CSE
• Introduction
• Defining a class
• Fields Declaration
• Methods declaration
• Creating Objects
• Accessing Class Members
• Constructors
• Self argument
• Static Members
What is Object Oriented Programming?
• Object-oriented programming (OOP) is a programming
paradigm based on the concept of "objects".

• The object contains both data and code: Data in the form of
properties (often known as attributes), and code, in the form
of methods (actions object can perform).
What is Object Oriented Programming ?

• An object-oriented paradigm is to design the program


using classes and objects.
• Python programming language supports different
programming approaches like functional
programming, modular programming.
• One of the popular approaches is object-oriented
programming (OOP) to solve a programming problem
is by creating objects
What is Object Oriented Programming in
Python
• An object has the following two characteristics:
• Attribute
• Behavior

• For example, A Car is an object, as it has the following properties:


• name, price, color as attributes
• breaking, acceleration as behavior
Class and Objects
• A class is a blueprint for the object. To create an object we require a
model or plan or blueprint which is nothing but class.

• A class contains the properties (attribute) and action (behavior) of the


object. Properties represent variables, and the methods represent
actions. Hence class includes both variables and methods.

• Object is an instance of a class. The physical existence of a class is


nothing but an object. In other words, the object is an entity that has
a state and behavior. It may be any real-world object like the mouse,
keyboard, laptop, etc.
Class and Objects
• Every object has the following properties.
• Identity: Every object must be uniquely identified.
• State: An object has an attribute that represents a state of an object, and it
also reflects the property of an object.
• Behavior: An object has methods that represent its behavior.

An object is a real-life entity.


It is the collection of various data and functions that operate on those
data.
Class and Objects
Class and Objects
Class and Objects
Class and Objects
Create a Class
In Python, class is defined by using the class keyword.

• class class_name:
• '''This is a docstring. I have created a new class'''
• <statement 1>
• <statement 2>
class ClassName:
• .
• . initializer
• <statement N> methods
Example: Define a class in Python
• In this example, we are creating a Person Class with name, sex, and
profession instance variables.
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession

# Behavior (instance methods)


def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)

# Behavior (instance methods)


def work(self):
print(self.name, 'working as a', self.profession)
Example
# Python3 program to demonstrate instantiating# a class
class Person:
# A simple class attribute
attr1 = "smart boy"
attr2 = "smart girl"

# A sample method
def fun(self):
print("I am a", self.attr1)
print("I am a", self.attr2)

# Driver code, Object instantiation


Rodger = Person()

# Accessing class attributes, and method through objects


print(Rodger.attr1)
Rodger.fun()
Create Object of a Class
• The object is created using the class name.
• When we create an object of the class, it is called instantiation.
• The object is also called the instance of a class.

•<object-name> = <class-name>(<arguments>)

•for example
• jessa = Person('Jessa', 'Female', 'Software Engineer')
# Python program to demonstrate instantiating a class
class Person:
# A simple class attribute
attr1 = "smart boy"
attr2 = "smart girl"

# A sample method
def fun(self):
print("I am a", self.attr1)
print("I am a", self.attr2)

def greet(self):
print("hope you are doing well")
# Driver code
# Object instantiation

# Accessing class attributes and method through objects


print(Rodger.attr1)
print(Rodger.attr2)
Rodger.fun()
Rodger.greet()
Object Creation
class Student:

# initialize instance variable


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

# instance Method
def show(self):
print('Hello, my name is', self.name)

# create object using constructor


s1 = Student('Emma')
s1.show()
Example: class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession

# Behavior (instance methods)


def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)

# Behavior (instance methods)


def work(self):
print(self.name, 'working as a', self.profession)

# create object of a class


jessa = Person('Jessa', 'Female', 'Software Engineer')

# call methods
jessa.show()
jessa.work()
Constructor
• A constructor is a special method used to create and initialize an object of a
class.
• Constructors are used to initializing the object’s state.
• This method is defined in the class.
• The constructor is executed automatically at the time of object creation.
• The primary use of a constructor is to declare and initialize data member/ instance
variables of a class. The constructor contains a collection of statements (i.e., instructions)
that executes at the time of object creation to initialize the attributes of an object.

• For example, when we execute obj = ClassName(), Python gets to know that
obj is an object of ClassName and calls the constructor of that class to create
an object.
• On the other hand, a destructor is used to destroy the object.
Constructor
• In Python, Object creation is divided into two parts in Object Creation
and Object initialization

• Internally, the __new__ is the method that creates the object


• And, using the __init__() method we can implement constructor to
initialize the object.
Syntax of a constructor
def __init__(self):
# body of the constructor

• def: The keyword is used to define function.


• __init__() Method: It is a reserved method. This method gets called
as soon as an object of a class is instantiated.
• self: The first argument self refers to the current object.
Create a Constructor in Python
class Student:
• In this example, we’ll
# constructor
create a Class Student # initialize instance variable
with an instance def __init__(self, name):
variable student print('Inside Constructor')
name. we’ll see how self.name = name
print('All variables initialized')
to use a constructor
to initialize the # instance Method
student name at the def show(self):
time of object print('Hello, my name is', self.name)
creation.
# create object using constructor
s1 = Student('Emma')
s1.show()
Constructor Example
# Sample class with init method
class Person:

# init method or constructor


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

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()
Constructor
• Note:

• For every object, the constructor will be executed only once. For
example, if we create four objects, the constructor is called four
times.
• In Python, every class has a constructor, but it’s not required to define
it explicitly. Defining constructors in class is optional.
• Python will provide a default constructor if no constructor is defined.
Types of Constructors
• In Python, we have the following
three types of constructors.

1. Default Constructor
2. Non-parametrized constructor
3. Parameterized constructor
Default Constructor
• Python will provide a default constructor if no
constructor is defined. Python adds a default
constructor when we do not include the constructor in
the class or forget to declare it. It does not perform
any task but initializes the objects. It is an empty class Employee:
constructor without a body.
def display(self):
• If you do not implement any constructor in your class print('Inside Display')
or forget to declare it, the Python inserts a default
constructor into your code on your behalf. This
constructor is known as the default constructor. emp = Employee()
emp.display()
• It does not perform any task but initializes the objects.
It is an empty constructor without a body.
• If you implement your constructor, then the default
constructor will not be added.
Non-Parametrized Constructor
class Company:
• A constructor without any # no-argument constructor
arguments is called a non- def __init__(self):
parameterized constructor. This self.name = "PYnative"
type of constructor is used to self.address = "ABC Street"
initialize each object with default
# a method for printing data members
values. def show(self):
print('Name:', self.name, 'Address:', self.address)

• This constructor doesn’t accept the # creating object of the class


arguments during object creation. cmp = Company()
Instead, it initializes every object
with the same set of values. # calling the instance method using the object
cmp.show()
Parameterized Constructor
class Employee:
# parameterized constructor
• A constructor with defined parameters or def __init__(self, name, age, salary):
arguments is called a parameterized self.name = name
constructor. We can pass different values self.age = age
to each object at the time of creation self.salary = salary
using a parameterized constructor.
# display object
• The first parameter to constructor is self def show(self):
that is a reference to the being print(self.name, self.age, self.salary)
constructed, and the rest of the
arguments are provided by the # creating object of the Employee class
programmer. emma = Employee('Emma', 23, 7500)
emma.show()
• A parameterized constructor can have
any number of arguments. kelly = Employee('Kelly', 25, 8500)
kelly.show()
Constructor With Default Values
class Student:
# constructor with default values age and classroom
• Python allows us to define a def __init__(self, name, age=12, classroom=7):
constructor with default values. self.name = name
self.age = age
The default value will be used if self.classroom = classroom
we do not pass arguments to the
# display Student
constructor at the time of object def show(self):
creation. print(self.name, self.age, self.classroom)

# creating object of the Student class


emma = Student('Emma')
emma.show()

kelly = Student('Kelly', 13)


Emma 12 7 kelly.show()
Kelly 13 7
Thank You
Object Oriented
Programming
Dr. Bharat Singh
PhD, CSE
Contents
• Accessing Class Members
• Class Attribute
• Class Method
• Defining Funtion in class
• Destructor
• Self argument
Write a Python program to create a Vehicle class
with max_speed and mileage instance attributes.

class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage

modelX = Vehicle(240, 18)


print(modelX.max_speed, modelX.mileage)
Exercise: Write the code for the given class
and object
Exercise: Write the code for the
import math given class

and object class Circle:


def __init__(self, radius=1):
self.radius=radius
def getPerimeter(self):
return 2*self.radius*math.pi
def getArea(self):
return math.pi*self.radius*self.radius
def setradius(self, radius):
self.radius=radius

c1=Circle() #create default circle with radius=1


print("the area of the circle of radius ", c1.radius, "is"
,c1.getArea())

c2=Circle(5)
print("the area of the circle of radius ",c2.radius, " is"
,c2.getArea())

c3=Circle(25)

c4=Circle(125)
Write a Python program to create a calculator
class. Include methods for basic arithmetic
operations. # Define a class called Calculator to
perform basic arithmetic operations
class Calculator:
# Define a method for addition that takes
two arguments and returns their sum
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y !=0:
return x / y
else:
return("Cannot divide by zero.")

calculator = Calculator()
result = calculator.add(7,5)
print("the sum of 7 + 5 =", result)
Example class Car():
# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color

def show(self):
print("Model is", self.model )
print("color is", self.color )

# both objects have different self which contain their attributes


audi = Car("audi a4", "blue")
ferrari = Car("ferrari 488", "green")

audi.show() # same output as car.show(audi)


ferrari.show() # same output as car.show(ferrari)

print("Model for audi is ",audi.model)


print("Colour for ferrari is ",ferrari.color)
__init__() method
• The __init__ method is class GFG:
def __init__(self, name, company):
similar to constructors in C++ self.name = name
and Java. self.company = company

• Constructors are used to def __str__(self):


initializing the object’s state. return f"My name is {self.name} and I work in {self.company}."

• It runs as soon as an object of my_obj = GFG("John", "Hindustan Fertilizers")


print(my_obj)
a class is instantiated.
• The method is useful to do
any initialization you want to
do with your object.
__str__() method
• Python has a particular method class GFG:
called __str__(). def __init__(self, name, company):
self.name = name
self.company = company
• It is used to define how a class
object should be represented as a def __str__(self):
string. return f"My name is {self.name} and I work in {self.company}."

• When a class object is used to my_obj = GFG("John", "GeeksForGeeks")


create a string using the built-in print(my_obj)
functions print() and str(), the
__str__() function is
automatically used.
Class Attributes
• When we design a class, we use instance variables and class variables.

• In Class, attributes can be defined into two parts:

• Instance variables: The instance variables are attributes attached to


an instance of a class. We define instance variables in the
constructor ( the __init__() method of a class).

• Class Variables: A class variable is a variable that is declared inside of


class, but outside of any instance method or __init__() method.
Class Attributes

• Objects do not share instance attributes.


Instead, every object has its copy of the
instance attribute and is unique to each
object.
• All instances of a class share the class
variables. However, unlike instance
variables, the value of a class variable is not
varied from object to object.
• Only one copy of the static variable will be
created and shared between all objects of
the class.
Accessing properties and assigning values

• An instance attribute can be accessed or modified by using the dot


notation:

instance_name.attribute_name.
• A class variable is accessed or modified using the class name
class Student:
# class variables
school_name = 'ABC School'

# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age

s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)

# access class variable


print('School name:', Student.school_name)

# Modify instance variables


s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)

# Modify class variables


Student.school_name = 'XYZ School'
print('School name:', Student.school name)
Class Methods
• Inside a Class, we can define the following three types of methods.
• Instant Method, Class Method and static method

• Instance method: Used to access or modify the object state. If we use


instance variables inside a method, such methods are called instance
methods.
• Any method we create in a class will automatically be created as an
instance method unless we explicitly tell Python that it is a class or
static method.
Class Methods
• Class method: Used to access or modify the class state. In method
implementation, if we use only class variables, then such type of
methods we should declare as a class method. A class method is
bound to the class and not the object of the class. It can access only
class variables.
• Static method: It is a general utility method that performs a task in
isolation. Inside this method, we don’t use instance or class variable
because this static method doesn’t have access to the class attributes.
Class Methods
# class methods demo
class Student:
# class variable
school_name = 'ABC School'
Define and call an instance
# constructor
method and class method
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age s1 = Student("Harry", 12)
# instance method # call instance methods
def show(self): s1.show()
# access instance variables and class variables s1.change_age(14)
print('Student:', self.name, self.age, Student.school_name)
# instance method # call class method
def change_age(self, new_age): Student.modify_school_name('XYZ School')
# modify instance variable # call instance methods
self.age = new_age s1.show()
# class method
@classmethod
def modify_school_name(cls, new_name):
# modify class variable
cls.school_name = new_name
Modify Object Properties
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color

def show(self):
print("Fruit is", self.name, "and Color is", self.color)

# creating object of the class


obj = Fruit("Apple", "red")

# Modifying Object Properties


obj.name = "strawberry"

# calling the instance method using the object obj


obj.show()
# Output Fruit is strawberry and Color is red
Delete object properties
class Fruit:
def __init__(self, name, color):
• We can delete the self.name = name
object property by self.color = color

using the del keyword. def show(self):


After deleting it, if we print("Fruit is", self.name, "and Color is", self.color)
try to access it, we will # creating object of the class
get an error. obj = Fruit("Apple", "red")

# Deleting Object Properties


del obj.name

# Accessing object properties after deleting


print(obj.name)
# Output: AttributeError: 'Fruit' object has no attribute 'name'
Delete Objects
class Employee:
depatment = "IT"
• we can also delete the object
by using a del keyword. An def show(self):
print("Department is ", self.depatment)
object can be anything like,
class object, list, tuple, set, emp = Employee()
etc. emp.show()

# delete object
del emp

# Accessing after delete object


emp.show()
# Output : NameError: name 'emp' is not defined
Constructor With Default Values
class Student:
# constructor with default values age and classroom
• Python allows us to define a def __init__(self, name, age=12, classroom=7):
constructor with default values. self.name = name
self.age = age
The default value will be used if self.classroom = classroom
we do not pass arguments to the
# display Student
constructor at the time of object def show(self):
creation. print(self.name, self.age, self.classroom)

# creating object of the Student class


emma = Student('Emma')
emma.show()

kelly = Student('Kelly', 13)


Emma 12 7 kelly.show()
Kelly 13 7
Destructor
• Destructor is a special method that is called when an object gets
destroyed.
• Destructor is used to perform the clean-up activity before destroying
the object, such as closing database connections or filehandle.
• Python has a garbage collector that handles memory management
automatically. For example, it cleans up the memory when an object
goes out of scope.
• We must release or close the other resources object were using, such
as open files, database connections, cleaning up the buffer or cache.
To perform all those cleanup tasks we use destructor
Destructor
Destructor
• The destructor is the reverse of the constructor.
• The constructor is used to initialize objects, while the destructor is
used to delete or destroy the object that releases the resource
occupied by the object.
• In Python, destructor is not called manually but completely
automatic. destructor gets called in the following two cases
• When an object goes out of scope or
• The reference counter of the object reaches 0.

• The special method __del__() is used to define a destructor.


class Student:

# constructor
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('Object initialized')

def show(self):
print('Hello, my name is', self.name)

# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')

# create object
s1 = Student('Emma')
s1.show()

# delete object
del s1
Important Points to Remember about
Destructor
• The __del__ method is called for any class Vehicle:
object when the reference count for def __init__(self, speed):
that object becomes zero. self.speed = speed;
• The reference count for that object def __del__(self):
becomes zero when the application print('Release resources')
ends, or we delete all references
manually using the del keyword. # creating an object
car = Vehicle(350);
• The destructor will not invoke when
we delete object reference. It will # to delete the object explicitly
del car
only invoke when all references to
the objects get deleted.
The self Parameter Python
• The class contains instance variables and methods. class GFG:
• Whenever we define instance methods for a class, def __init__(self, name, company):
we use self as the first parameter, but it is not used self.name = name
when the method is called. self.company = company

• self is a parameter that references the object def show(self):


itself. print("Hello my name is " + self.name+" and I" +
• Using self, we can access the instance variable and " work in "+self.company+".")
instance method of the object.
obj = GFG("John", "GeeksForGeeks")
• The first argument self refers to the current object. obj.show()
• self in Python is equivalent to this in C++ or Java.
The self Parameter Python class Student:
# constructor
def __init__(self, name, age):
• Whenever we call an instance self.name = name
self.age = age
method through an object, the
Python compiler implicitly # self points to the current object
def show(self):
passes object reference as the # access instance variable using self
first argument commonly print(self.name, self.age)
known as self.
# creating first object
emma = Student('Emma', 12)
emma.show()

# creating Second object


kelly = Student('Kelly', 13)
kelly.show()
• It is not mandatory to name class GFG:
def __init__(somename, name, company):
the first parameter as a self. somename.name = name
We can give any name somename.company = company
whatever we like, but it has to def show(somename):
be the first parameter of an print("Hello my name is " + somename.name +
instance method. " and I work in "+somename.company+".")

obj = GFG("John", "GeeksForGeeks")


obj.show()
Constructor Overloading
class Student:
# one argument constructor
• Constructor overloading is a concept of
having more than one constructor with a def __init__(self, name):
different parameters list in such a way so print("One arguments constructor")
that each constructor can perform different self.name = name
tasks.
• For example, we can create a three # two argument constructor
constructor which accepts a different set of def __init__(self, name, age):
parameters print("Two arguments constructor")
self.name = name
• Python does not support constructor self.age = age
overloading.
• If we define multiple constructors then, the # creating first object
interpreter will considers only the last emma = Student('Emma')
constructor and throws an error if the
sequence of the arguments doesn’t match # creating Second object
as per the last constructor. kelly = Student('Kelly', 13)
Constructor Overloading
• while Python does not support class Person:
traditional method and def __init__(self, name, age=None):
constructor overloading. self.name = name
self.age = age
• You can leverage default values
and variable-length argument # Example Usage
lists to achieve similar person1 = Person(‘Alice’)
person2 = Person(’Bob ’, 25)
functionality.
# Output
print(person1.name, person1.age)
print(person2.name, person2.age)
Method overloading
• Two or more methods have the
same name but different
numbers of parameters or
different types of parameters, or
both. These methods are called
overloaded methods and this is
called method overloading.
Method overloading class MathOperations:
def add(self, a, b=None, c=None):
if b is not None and c is not None:
• while Python does not support return a + b + c
traditional method and constructor elif b is not None:
overloading. return a + b
else:
• You can leverage default values and return a
variable-length argument lists to
achieve similar functionality.
# Example Usage
• In this example, the math_obj = MathOperations()
MathOperations class defines an result1 = math_obj.add(5)
add method with optional result2 = math_obj.add(5, 10)
result3 = math_obj.add(5, 10, 15)
parameters b and c, allowing for
method overloading based on the # Output
number of arguments. print(result1)
print(result2)
print(result3)
Object Oriented
Programming
Dr. Bharat Singh
PhD, CSE
Contents
• Encapsulation in Python
• Need for Encapsulation
• Data Hiding using public, protected, and private members
• Data Hiding vs. Encapsulation
• Getter and Setter Methods
Encapsulation
• It describes the concept of
bundling data and methods
within a single unit.
• So when you create a class, it
means you are implementing
encapsulation.
• A class is an example of
encapsulation as it binds all the
data members (instance
variables) and methods into a
single unit.
Encapsulation
• It describes the concept of
bundling data and methods
within a single unit.
• So when you create a class, it
means you are implementing
encapsulation.
• A class is an example of
encapsulation as it binds all the
data members (instance
variables) and methods into a
single unit.
def __init__(self, name, salary,
project):
Encapsulation # data members
self.name = name
# method self.salary = salary
def work(self): self.project = project
print(self.name, 'is working on',
self.project)
# method
# creating object of a class # to display employee's details
emp = Employee('Jessa', 8000,
'NLP')
def show(self):
# accessing public data
# calling public method of the class member
emp.show()
emp.work()
print("Name: ", self.name,
'Salary:', self.salary)
Encapsulation
• Using encapsulation, we can hide an object’s internal representation
from the outside. This is called information hiding.

• Also, encapsulation allows us to restrict accessing variables and


methods directly and prevent accidental data modification by creating
private data members and methods within a class.

• Encapsulation is a way to can restrict access to methods and variables


from outside of class. Whenever we are working with the class and
dealing with sensitive data, providing access to all variables used within
the class is not a good choice.
Access Modifiers in Python
• Access modifiers limit access to the
variables and methods of a class.
• Python provides three types of access
modifiers private, public, and protected.

• Public Member: Accessible anywhere


from otside of class.
• Private Member: Accessible within the
class
• Protected Member: Accessible within the
class and its sub-classes
Access modifiers
• A Class in Python has three types of access modifiers:

• Public Access Modifier: Theoretically, public methods and fields can


be accessed directly by any class.
• Protected Access Modifier: Theoretically, protected methods and
fields can be accessed within the same class it is declared and its
subclass.
• Private Access Modifier: Theoretically, private methods and fields
can be only accessed within the same class it is declared.
class Employee:
# constructor
Public Member def __init__(self, name, salary):
# public data members
self.name = name
• Public data members are self.salary = salary
accessible within and outside of
a class. # public instance methods
• All member variables of the def show(self):
class are by default public. # accessing public data member
print("Name: ", self.name, 'Salary:',
self.salary)

# creating object of a class


emp = Employee('Jessa', 10000)

# accessing public data members


print("Name: ", emp.name, 'Salary:',
Private Member
class Employee:
• Private members are accessible # constructor
def __init__(self, name, salary):
only within the class, and we # public data member
can’t access them directly from self.name = name
the class objects. # private member
self.__salary = salary
• To define a private variable add
# creating object of a class
two underscores as a prefix at emp = Employee('Jessa', 10000)
the start of a variable name.
# accessing private data members
print('Salary:', emp.__salary)

• Output: AttributeError: 'Employee' object has no attribute '__salary'


# Python program to demonstrate private members Creating a
Base class
class Base:
def __init__(self):
self.a = "IIM Ranhci"
self.__c = "IIIT Ranchi"
# 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
Private Member
• We can access private members from outside of a class using the
following two approaches
• Create public method to access private members
• Use name mangling
Public method to access private members
class Employee:
# constructor
• Access Private member outside def __init__(self, name, salary):
of a class using an instance # public data member
self.name = name
method # private member
self.__salary = salary

# public instance methods


def show(self):
# private members are accessible from a class
print("Name: ", self.name, 'Salary:', self.__salary)

# creating object of a class


emp = Employee('Jessa', 10000)

# calling public method of the class


emp.show()
Name Mangling
class Employee:
• Name Mangling to access private # constructor
members def __init__(self, name, salary):
# public data member
• The name mangling is created on an self.name = name
identifier by adding two leading # private member
self.__salary = salary
underscores and one trailing
underscore, like this # creating object of a class
emp = Employee('Jessa', 10000)
_classname__dataMember
, where classname is the current print('Name:', emp.name)
# direct access to private member using name mangling
class, and data member is the print('Salary:', emp._Employee__salary)
private variable name.
# Creating a Base class
class Base:
# Declaring public method
def fun(self):
print("Public method")
# Driver code
# Declaring private method
obj1 = Base()
def __fun(self):
print("Private method")
# Calling public method
# Creating a derived class
obj1.fun()
class Derived(Base):
def __init__(self):
obj2 = Derived()
# Calling constructor of
obj2.call_public()
# Base class
Base.__init__(self)
# Uncommenting obj1.__fun() will
def call_public(self):
# raise an AttributeError
# Calling public method of base class
print("\nInside derived class")
# Uncommenting obj2.call_private()
self.fun()
# will also raise an AttributeError
def call_private(self):
# Calling private method of base class
self.__fun()
# base class
Protected Member class Company:
def __init__(self):
# Protected member
self._project = "NLP"
• Protected members are accessible
within the class and also available to # child class
class Employee(Company):
its sub-classes. def __init__(self, name):
• To define a protected member, self.name = name
prefix the member name with a Company.__init__(self)

single underscore _. def show(self):


print("Employee name :", self.name)
# Accessing protected member in child class
• Protected data members are used print("Working on project :", self._project)
when you implement inheritance c = Employee("Jessa")
and want to allow data members c.show()
access to only child classes.
# Direct access protected data member
print('Project:', c._project)
Example # program to illustrate protected data members in a class
# Defining a class
class Student:

# protected data members


_name = "R2J"
_roll = 1706256

# public member function


def displayNameAndRoll(self):

# accessing protected data members


print("Name: ", self._name)
print("Roll: ", self._roll)

# creating objects of the class


obj = Geek()

# calling public member functions of the class


obj.displayNameAndRoll()
# derived class
class MBA(Student):
# program to illustrate protected access modifier in a class def __init__(self, name, roll, branch):
Student.__init__(self, name, roll, branch)
# super class def displayDetails(self):
class Student: # accessing protected data members of super class
print("Name:", self._name)
# protected data members # accessing protected member functions of super class
_name = None self._displayRollAndBranch()
_roll = None
_branch = None stu = Student("Alpha", 1234567, "Computer Science")
print(dir(stu))
# constructor # protected members and methods can be still accessed
def __init__(self, name, roll, branch): print(stu._name)
self._name = name stu._displayRollAndBranch()
self._roll = roll # Throws error
self._branch = branch # print(stu.name)
# stu.displayRollAndBranch()
# protected member function # creating objects of the derived class
def _displayRollAndBranch(self): obj = MBA("R2J", 1706256, "Information Technology")
# accessing protected data members print("")
print("Roll:", self._roll) print(dir(obj))
print("Branch:", self._branch) # calling public member functions of the class
obj.displayDetails()
• In the above program, _name, _roll, and _branch are protected data
members and _displayRollAndBranch() method is a protected
method of the super class Student. The displayDetails() method is a
public member function of the class Geek which is derived from the
Student class, the displayDetails() method in Geek class accesses the
protected data members of the Student class.
# program to illustrate protected access modifier in a class
# super class
class Student: stu = Student("Alpha", 1234567, "Computer Science")
# protected data members print(dir(stu))
__name = None print(‘ ’)
__roll = None
__branch = None # Throws error
# constructor # obj.__name
def __init__(self, name, roll, branch): # obj.__roll
self.__name = name # obj.__branch
self.__roll = roll # obj.__displayDetails()
self.__branch = branch
# protected member function # To access private members of a class
def __displayRollAndBranch(self): print(obj._Student__name)
# accessing protected data members print(obj._Student__roll)
print("Roll:", self.__name) print(obj._Student__branch)
print("Roll:", self.__roll) obj._Student__displayDetails()
print("Branch:", self.__branch)
print("")
# public member function
def accessPrivateFunction(self): # calling public member function of the class
# accessing private member function obj.accessPrivateFunction()
self.__displayDetails()
Getters and Setters in Python
• The primary purpose of using
getters and setters in object-
oriented programs is to ensure
data encapsulation.

• Use the getter method to access


data members
• Use the setter methods to
modify the data members.
class Student:
def __init__(self, name, age):
# private member
self.name = name
self.__age = age

# getter method
def get_age(self):
return self.__age

# setter method
def set_age(self, age):
self.__age = age

stud = Student('Jessa', 14)

# retrieving age using getter


print('Name:', stud.name, stud.get_age())

# changing age using setter


stud.set_age(16)

# retrieving age using getter


print('Name:', stud.name, stud.get_age())
Advantages of Encapsulation
• Security: The main advantage of using encapsulation is the security of the
data. Encapsulation protects an object from unauthorized access. It allows
private and protected access levels to prevent accidental data modification.
• Data Hiding: The user would not be knowing what is going on behind the
scene. They would only be knowing that to modify a data member, call the
setter method. To read a data member, call the getter method. What these
setter and getter methods are doing is hidden from them.
• Simplicity: It simplifies the maintenance of the application by keeping
classes separated and preventing them from tightly coupling with each
other.
• Aesthetics: Bundling data and methods within a class makes code more
readable and maintainable
What are Private and Protected Members in
Python Classes?
• Private Members: Members with • Protected Members: Members
double underscores (__) are with a single underscore (_) are
private. protected.
• They are intended to be • They are intended for use within
accessed only within the class the class and its subclasses.
where they are defined.
• Python uses name mangling to • This is a convention and does
make these members harder to not enforce strict access control.
access from outside the class.
What are Key Differences Between
Encapsulation and Abstraction?
• Encapsulation: • Abstraction:
• Definition: The bundling of data and • Definition: The concept of hiding
complex implementation details and
methods that operate on the data showing only the essential features
into a single unit, with controlled of an object.
access to the internal state. • Purpose: To simplify interaction with
objects by focusing on high-level
• Purpose: To protect an object’s operations rather than
internal state and expose a implementation details.
controlled interface. • Implementation: Achieved through
• Implementation: Achieved through abstract classes and methods,
interfaces, and high-level class
private and protected members. design.
Inheritance
• Inheritence
• Types of inheritance
• super() in python
• method overridien
• Method Resolution Order
Inheritence
• The process of inheriting the properties of the parent class into a
child class is called inheritance.
• The existing class is called a base class or parent class and the new
class is called a subclass or child class or derived class.
• The main purpose of inheritance is the reusability of code because
we can use the existing class to create a new class instead of creating
it from scratch.
• In inheritance, the child class acquires all the data members,
properties, and functions from the parent class.
• Also, a child class can also provide its specific implementation to the
methods of the parent class.
Inheritence
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Creating a Parent Class Creating a Child Class
A parent class is a class whose properties A child class is a class that drives the properties from its parent
are inherited by the child class. class.

# A Python program to demonstrate inheritance


class Person(object):

# Constructor class Emp(Person):


def __init__(self, name, id):
self.name = name def Print(self):
self.id = id print("Emp class called")
# To check if this person is an employee Emp_details = Emp("Mayank", 103)
def Display(self):
print(self.name, self.id) # calling parent class function
Emp_details.Display()
# Driver code
emp = Person("Satyam", 102) # An Object of Person # Calling child class function
emp.Display() Emp_details.Print()
Types Of Inheritance
Single Inheritance # Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
• In single inheritance, a child
class inherits from a single- # Child class
parent class. Here is one child class Car(Vehicle):
def car_info(self):
class and one parent class. print('Inside Car class')

# Create object of Car


car = Car()

# access Vehicle's info using car object


car.Vehicle_info()
car.car_info()
# Parent class 1
class Person:
def person_info(self, name, age):
Multiple Inheritance print('Inside Person class')
print('Name:', name, 'Age:', age)

# Parent class 2
• one child class can inherit from class Company:
multiple parent classes. So here def company_info(self, company_name, location):
print('Inside Company class')
is one child class and multiple print('Name:', company_name, 'location:', location)
parent classes.
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)

# Create object of Employee


emp = Employee()

# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee info(12000, 'Machine Learning')
Multilevel inheritance
• a class inherits from a child class
or derived class.
• Suppose three classes A, B, C. A
is the superclass, B is the child
class of A, C is the child class of
B.
• chain of classes is called
multilevel inheritance.
# Base class

Multilevel inheritance
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')

# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')

# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')

# Create object of SportsCar


s_car = SportsCar()

# access Vehicle's and Car info using SportsCar object


s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Hierarchical Inheritance
• More than one child class is
derived from a single parent
class. In other words, we can say
one parent class and multiple
child classes.
class Vehicle:
def info(self):
print("This is Vehicle")

class Car(Vehicle):
• Example def car_info(self, name):
print("Car name is:", name)

• Let’s create ‘Vehicle’ as a parent class Truck(Vehicle):


def truck_info(self, name):
class and two child class ‘Car’ print("Truck name is:", name)
and ‘Truck’ as a parent class.
obj1 = Car()
obj1.info()
obj1.car_info('BMW')

obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
class Vehicle:
def vehicle_info(self):
Hybrid Inheritance print("Inside Vehicle class")

class Car(Vehicle):
def car_info(self):
• When inheritance is consists of print("Inside Car class")
multiple types or a combination class Truck(Vehicle):
of different inheritance is called def truck_info(self):
hybrid inheritance. print("Inside Truck class")

# Sports Car can inherits properties of Vehicle and Car


class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside SportsCar class")

# create object
s_car = SportsCar()

s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy