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

Unit-IV-OOP-in-Python(NEP)

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, and key principles such as inheritance, encapsulation, and polymorphism. It contrasts OOP with Procedural Programming (POP), highlighting the benefits of OOP like modularity, maintainability, and real-world modeling. Additionally, it covers class creation, data hiding, constructors, and built-in class attributes in Python.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-IV-OOP-in-Python(NEP)

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, and key principles such as inheritance, encapsulation, and polymorphism. It contrasts OOP with Procedural Programming (POP), highlighting the benefits of OOP like modularity, maintainability, and real-world modeling. Additionally, it covers class creation, data hiding, constructors, and built-in class attributes in Python.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Programming in Python

(23DCE2101)

(As per NEP 2023 pattern)


Prof. S.M. Sabale
Head of Computer Engineering (Diploma)
Dr. Babasaheb Ambedkar Technological University, Lonere
Unit-IV

Object Oriented Programming


in
Python
OOP Concepts
1. Class, state and behaviour
2. Object
3. Data Member
4. Instance Variable
5. Class Variable
6. Instance
7. Instantiation
8. Method
9. Function Overloading
10. Encapsulation
11. Inheritance
12. Polymorphism
Fundamental building blocks of OOP
Object-oriented programming (OOP) is a way of structuring software around self-
contained objects that combine data (properties) and the actions (methods) that
operate on that data.
• Now that we've grasped the essence of OOP, let's delve into the fundamental
building blocks that make it tick:
Objects: Objects act as the actors in your software play. Each object represents a
real-world entity, like a car, a user, or a product. They encapsulate data (think
properties or attributes) that define their characteristics, such as a car's color, a
user's name, or a product's price.
• But objects aren't passive bystanders! They also possess functionalities (methods
or functions) that dictate how they interact with the world. A car object can
accelerate, a user object can login, and a product object can be added to a
shopping cart.
Classes: Classes act as blueprints for creating objects. They define the properties
(data type) and methods (functionality) that all objects of a particular type will
share.
• Think of a class as a cookie cutter for objects – it specifies the shape (properties)
and the actions (methods) they can perform. For instance, a "Car" class might
define attributes like color and model, and methods like accelerate() and brake().
• A class is a blueprint for how to define something. It doesn’t actually contain any
data. While the class is the blueprint, an instance is an object that’s built from a
class and contains real data.
Attributes: These are the data points or characteristics that define an object's
state. They provide the details about an object, such as a car's color being "red"
or a user's name being "Alice". Attributes are essentially variables specific to an
object, allowing you to store and manipulate its data.
Methods: These are the functions or actions that objects can perform. They
dictate how objects interact with the world and other objects. A car object's
accelerate() method might increase its speed, while a user object's login()
method might verify their credentials. Methods operate on the object's
attributes, allowing you to modify or utilize its data.
Main Principles of Object-Oriented Programming
• Now that we have objects with their own properties and functionalities, let's
explore how they can interact and build complex systems:
Inheritance: This allows you to create new classes (subclasses) that inherit
properties and behaviors (methods) from existing classes (superclasses).
• Suppose that there is a "SportsCar" class that inherits properties and methods
from a more general "Car" class. This allows the "SportsCar" to reuse existing
functionality (accelerate, brake) while adding its own unique features (turbo
boost). Inheritance promotes code reusability and creates a hierarchy of related
objects.
Encapsulation: This concept focuses on protecting an object's internal data
(attributes) by controlling access through methods. Think of it as a secure vault
for the object's data. Encapsulation ensures data integrity and prevents
unauthorized modifications.
Polymorphism: This powerful concept allows objects of different classes to
respond differently to the same message. For instance, a "draw()" method might
display a car on the screen, but it could also display a user profile picture or a
product image, depending on the object it's called on. Polymorphism adds
flexibility and simplifies code.
Abstraction: This concept focuses on hiding unnecessary details and exposing
essential functionalities. Methods act as the interface, allowing us to interact with
objects without worrying about their internal workings. Abstraction promotes
code clarity and maintainability.
Benefits of Object-Oriented Programming
Object-Oriented Programming (OOP) offers a powerful approach to
software development, bringing several advantages to the table. Here's a
breakdown of some key benefits that make OOP a popular choice for many
programmers:
• Modular and Reusable Code: OOP promotes code modularity by
organizing software around self-contained objects. These objects
encapsulate data and functionality, making them reusable across different
parts of your program.
• Maintainability: Since objects are self-contained units, modifying code
becomes easier. Changes made within an object are less likely to break
other parts of the program, promoting cleaner and more maintainable
codebases. As your project grows, OOP structures make it easier to
understand and update individual components.
• Scalability and Flexibility: OOP allows for easier extension and growth of your
software. Inheritance, a core OOP concept, lets you create new classes
(subclasses) that inherit properties and behaviors from existing ones
(superclasses). This promotes code reusability and enables you to build complex
systems by layering functionalities on top of each other.
• Data Protection and Encapsulation: OOP promotes data protection through
encapsulation. Data within an object is often hidden (private) and accessed
through controlled methods (public). This prevents accidental modification of
crucial data, ensuring the integrity and consistency of your program's state.
• Real-World Modeling: OOP allows you to model real-world entities using objects.
This makes your code more intuitive and easier to understand, especially for
complex systems that mirror real-world interactions.
• Improved Code Readability: By separating data and functionality into well-
defined objects and classes, OOP promotes cleaner and more readable code. This
improves code clarity for both you and other developers working on the project,
making it easier to understand and maintain in the long run.
Differences Between Procedural & Object-
Oriented Programming
• Procedural Programming (POP) breaks tasks into step-by-step functions, while
Object-Oriented Programming (OOP) builds with objects that hold data and
actions.
Understanding Procedural Programming (POP)
• Suppose that you are building a house, you may follow a detailed plan and
carefully place each brick one at a time. This is like Procedural Programming
(POP), perfect for simple tasks with clear steps. But what happens if you're
building a skyscraper? Object-Oriented Programming (OOP) comes in; it lets you
make reusable wall, door, and window blueprints (classes), making complex
projects efficient and organized. This guide dives into both POP and OOP, helping
you decide which "toolbox" is best for the job at hand.
• Procedural Programming (POP) is a structured programming approach where the
program logic is decomposed into a sequence of self-contained procedures or
functions. Each procedure has a clear purpose and can be invoked independently,
promoting modularity and code organization.

• POP likes building with LEGOs. Each LEGO brick represents a simple instruction.
By snapping them together in a specific order, you create a functioning program.
In POP, this means breaking down tasks into clear, step-by-step instructions that
the computer executes sequentially.
Procedural Programming (POP) is a structured programming approach.
Understanding Object-Oriented Programming (OOP)

• In contrast to POP, OOP offers a data-centric approach. It revolves


around creating objects that represent real-world entities with their
properties and functionalities. OOP emphasizes concepts like
inheritance, polymorphism, and encapsulation to create reusable,
maintainable, and modular programs, particularly suited for complex
projects.
• Object-oriented programming is a way of structuring software around
self contained objects that combine data (properties) and the actions
(methods) that operate on that data.
Differences Between Procedural & Object-Oriented Programming

Object-Oriented Programming
Feature Procedural Programming (POP)
(OOP)
Focus Procedures (functions) Objects (data + behavior)
Program Structure Sequence of functions Objects interacting with each other
Data Organization Global/local variables, function arguments Encapsulated within objects
High through inheritance and
Code Reusability Limited, prone to duplication
polymorphism
Improved due to encapsulation and
Maintainability Challenging for large projects
inheritance
Complex projects, code reusability,
Suitability Simple tasks, smaller projects, education
real-world modelling
Example Languages C, FORTRAN, Pascal C++, Java, Python, C#
POP vs. OOP: Which to Choose?
• Consider POP for: Simple, well-defined tasks, Smaller projects, Educational
purposes
• Consider OOP for: Complex projects, Code reusability, Large-scale
development
• Hybrid Approaches: In some cases, you might consider a hybrid approach
that combines elements of both POP and OOP. Here's when it might be
beneficial:
• Large projects with well-defined subtasks: If your project has a complex
overall structure but includes well-defined subtasks, you can leverage OOP for
the main structure and utilize POP for simpler subtasks within the objects.
• Phased development: When starting a project with a less clear scope, you
might begin with a simpler POP approach for initial development and then
gradually migrate towards OOP as requirements solidify and the project grows
in complexity.
OOP vs Procedural/Structured Programming
Procedural Oriented Programming Object-Oriented Programming
In procedural programming, the program is In object-oriented programming, the program is
divided into small parts called functions. divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows a bottom-


approach. up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.
Continued…
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance. data hiding and inheritance is used.

In procedural programming, the function is more In object-oriented programming, data is more


important than the data. important than function.

Procedural programming is based on the unreal Object-oriented programming is based on


world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the concept
procedure abstraction. of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Classes
• Creating classes:
Syntax:
class Classname:
‘optional class documentation string’
# list of python class variables
# python class constructor
# python class method definitions
Example:
class Car:
pass
• In a class we can define variables, functions, etc. While writing any function
in a class we have to pass at least one argument that is called ‘self
parameter’.
• The self parameter is a reference to the class itself and is used to access
variables that belongs to the class. It does not have to be named self, we
can call it whatever we like, but it has to be the first parameter of any
function in the class.
• We can write a class on interactive interpreter or in .py file.
class student:
def display(self):
print(“Hello Python”)
• In python programming, self is default variable that contains the address of
the instance of the current class. So we can use self to refer to all the
instance variables and instance methods.
Objects and creating classes
• Example:
s1=student()
s1.display()
• Program for demonstration:
class student:
def display(self):
print(“Hello Python”)
s1=student()
s1.display()
Output:
Hello Python
• Class with get and put method.
Program: put-get.py

Instance variable and class variable:


• Instance variable is defined in a method and its scope is only within the
object that defines it. Instance attribute is unique to each object(instance).
Every object of that class has its own copy of that variable. Any changes made
to the variable don’t reflect in other objects of that class.
• Class variable is defined in the class and can be used by all the instances of
that class. Class attribute is same for all objects. And there is only one copy of
that variable that is shared with all objects. Any changes made to that
variable will reflect in all other objects.
• Instance variables are unique for each instance, while class variables are
shared by all the instances.
Program: instance-class-variable.py
Data Hiding
• Hide internal object details(data members)
• Data hiding ensures exclusive data access to class members and
protects object integrity by preventing unintended or intended
changes.
• Objects attributes may or may not be visible outside class definition.
• Attributes with a double underscore (__) prefix are called as private
variables and are not directly visible to outsiders i.e. accessible only
within a class where it is declared.
• Program: data-hiding.py
Data encapsulation and data abstraction
• Encapsulation is a process to bind data and functions together into a single unit
i.e. class while abstraction is a process in which the data inside the class is hidden
from the outside world. It hides the sensitive information.
• To support encapsulation, declare the methods or variables as private in the class
(by double underscore prefix).

Sr. No. Types Description


1 public methods Accessible from anywhere i.e. inside the class in which they are defined, in
the sub class, in the same script file as well as outside the script file.
2 private methods Accessible only in their own class. Starts with two underscores.
3 public variables Accessible from anywhere
4 private variables Accessible only in there own class or by a method if defined. Starts with two
underscores.
• Program: access-modi-encap-abstraction.py
Constructor
• Constructor is a special type of method used to initialize the instance
members of the class at the time creating an object.
• Constructor does two things:
It creates an object in the memory for the class.
It invokes the class’s __init__ method to initialize the object.
• Python class constructor is the first piece of the code to be executed when
we create a new object of a class.
• In Python, the __init__ () method is called the constructor and is always
called when an object is created.
• Syntax:
def __init__(self):
# body of the constructor
• Programs: constructor.py, rectangle.py
• Default Constructor: It is simple constructor which does not accept any
arguments. It’s definition has only one argument which is a reference to
the instance being constructed, and that is self.
• Program: default-constrctor.py, default-constrctor-1.py

• Parameterized Constructor: First argument is self and rest of the


arguments are provided by the programmer.
• Program: parameterized-constructor.py

• Destructor: A class can define a method called a destructor with the help
of __del__(). This method is invoked automatically when the
instance(object) is about to be destroyed.
• It is mostly used to clean up any non-memory resources used by an
instance(object).
• Program: destructor.py
Built-in class attributes
Python offers many tools and features to simplify software
development. Built-in class attributes are the key features that enable
developers to provide important information about classes and their
models. These objects act as hidden gems in the Python language,
providing insight into the structure and behavior of objects.
In Python, built-in class attributes are properties associated with a class
itself, rather than its instances. These attributes provide metadata
about the class and are accessible.
Every Python class keeps following built-in attributes and they can be
accessed using dot operator like any other attribute:
• __dict__: It displays the dictionary in which the class’s namespace is stored.
• __name__: It displays the name of the class.
• __bases__: It displays the tuple that contains the base classes, possibly
empty. It displays them in the order in which they occur in the base class list.
• __doc__: It displays the documentation string of the class. It displays none if
the docstring isn’t given.
• __module__: It displays the name of the module in which the class is defined.
Generally, the value of this attribute is “__main__” in interactive mode.
• Program: builtin-attributes.py
Method Overloading
• It is the ability to define the method with the same name but with the different
number of arguments and data types to perform different tasks.
• Python does not support method overloading, i.e. it is not possible to define
more than one method with the same name in a class in Python. This is because
method arguments in Python do not have a type. A method accepting one
argument can be called with an integer value, a string or a double, etc.
• Ex: class demo:
def method(self, a):
print(a)
Output:
50
obj = demo()
Minakshi
obj.method(50)
100.3
obj.method(‘Minakshi’)
obj.method(100.3)
Using default arguments (method overloading)
• It is possible to provide default values to method arguments while
defining a method. If method arguments are supplied default values,
then it is not mandatory to supply those arguments while calling
method as shown in the program – defaultarguments.py
Inheritance: Extending a class
• The mechanism of deriving a new class from an old one is called inheritance. The
old class is called as base class or super class or parent class and the new one is
called the subclass or derived class or child class.
• The inheritance allows the subclasses to inherit all the variables and methods of
their parent classes hence acquiring the properties of parent class. (Reusabaility)

• Defining a subclass
• Syntax:
class A:
# attributes of class A
class B(A):
# class B inheriting the properties of class A
# more class B properties
Single Inheritance
• Syntax:
class A:
# attributes of class A
class B(A):
# class B inheriting the properties of class A
# more class B properties
Programs: singleinheritance.py, singleinheritance-constructor.py
Multilevel Inheritance
• Syntax:
class A:
# attributes of class A
class B(A):
# class B inheriting the properties of class A
# more class B properties
class C(B):
# class C inheriting the properties of class B
# more class C properties

Program: Multilevelinheritance.py
Multiple Inheritance
• Syntax:
class A:
# attributes of class A
class B:
# Attributes of class B
class C(A, B):
# class C inheriting the properties of class A and class B
# more class C properties

Program: Multiple-inheritance.py
Hierarchical Inheritance
• Syntax:
class A:
# attributes of class A
class B(A):
# class B inheriting the properties of class A
# Attributes of class B
class C(A):
# class C inheriting the properties of class A
# more class C properties

Program: hierarchical-inheritance.py
Method Overriding
• Method Overriding is the ability of a class to change the implementation
(behaviour) of a method provided by one of its base class. It is thus a strict part of
the inheritance mechanism.
• Program: method-overriding.py
• In inheritance, delegation occurs automatically, but if a method is overridden the
implementation of the parent is not considered at all. So, if you want to run the
implementation of one or more of the ancestors of your class, you have to call
them explicitly.
• Using super() method: The super() method gives you access to methods in a
superclass that inherits from it.
• The super() method also returns a temporary object of the superclass that then
allows you to call that superclass’s methods.
• Program: method-overriding-super().py

You might also like