1. Object-Oriented Programming
Course: Introduction to Programming and Data Structures
Dr. Laltu Sardar
Institute for Advancing Intelligence (IAI),
TCG Centres for Research and Education in Science and Technology (TCG Crest)
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 1 / 49
2. 1 Introduction to Object-Oriented Programming
Comparison of Programming Paradigms
Classes and Objects
Creating and Using Classes
2 Encapsulation
What is Encapsulation?
Private and Public Members
Example of Encapsulation in Python
Explanation of Code
Why Encapsulation?
3 Inheritance
What is Inheritance?
Types of Inheritance
Example of Single Inheritance
Explanation of Code
Example of Multilevel Inheritance
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 2 / 49
3. Explanation of Code
Advantages of Inheritance
4 Polymorphism
What is Polymorphism?
Types of Polymorphism
Polymorphism with Method Overriding
Explanation of Code
Polymorphism through Duck Typing
Explanation of Duck Typing Code
Advantages of Polymorphism
5 Abstraction
What is Abstraction?
Abstract Classes in Python
Example of Abstract Class
Explanation of Abstract Class Example
Use of Abstraction in Python
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 3 / 49
4. Real-World Example of Abstraction
Explanation of Real-World Example
Advantages of Abstraction
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 4 / 49
5. Introduction to Object-Oriented Programming
Introduction to Object-Oriented
Programming
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 5 / 49
6. Introduction to Object-Oriented Programming Comparison of Programming Paradigms
Programming Paradigms I
Procedural Programming:
Focuses on a sequence of instructions or procedures.
Functions are the main building blocks.
Data and functions are separate; there is no concept of objects.
Example: C, Pascal.
Object-Oriented Programming (OOP):
Organizes code into objects which combine both data
(attributes) and behavior (methods).
Promotes concepts like inheritance, polymorphism, and
encapsulation.
Useful for modeling complex systems and relationships between
entities.
Example: Python, Java, C++.
Functional Programming:
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 6 / 49
7. Introduction to Object-Oriented Programming Comparison of Programming Paradigms
Programming Paradigms II
Treats computation as the evaluation of mathematical functions.
Avoids changing-state and mutable data.
Emphasizes immutability, higher-order functions, and recursion.
Example: Haskell, Lisp, Python (can support functional
programming).
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 7 / 49
8. Introduction to Object-Oriented Programming Comparison of Programming Paradigms
Key Dierences between the Paradigms I
State Management:
Procedural: Direct manipulation of state through variables.
OOP: State is encapsulated within objects and managed through
methods.
Functional: Encourages immutability; no direct state
manipulation.
Code Reuse:
Procedural: Functions can be reused, but lacks sophisticated
reuse mechanisms.
OOP: Code reuse through inheritance and polymorphism.
Functional: Code reuse through higher-order functions and pure
functions.
Modularity:
Procedural: Achieved through functions and procedures.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 8 / 49
9. Introduction to Object-Oriented Programming Comparison of Programming Paradigms
Key Dierences between the Paradigms II
OOP: Achieved through classes and objects.
Functional: Achieved through functions and composability.
Approach to Problems:
Procedural: Focuses on breaking down the problem into
sequential steps.
OOP: Models problems by dening objects and their
interactions.
Functional: Focuses on dening mathematical functions to
transform data.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 9 / 49
10. Introduction to Object-Oriented Programming Classes and Objects
Classes and Objects
A Class is a blueprint for creating objects.
An Object is an instance of a class.
Objects encapsulate both data (attributes) and behavior
(methods).
Classes promote code reuse through inheritance.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 10 / 49
11. Introduction to Object-Oriented Programming Creating and Using Classes
Creating and Using Classes: Example
Example of creating and using a class in Python:
1 class Car:
2 def __init__(self , brand , model , year):
3 self.brand = brand
4 self.model = model
5 self.year = year
6
7 def display_info(self):
8 return f'{self.year} {self.brand} {self.model}'
9
10 # Create an object of class Car
11 my_car = Car(Toyota, Corolla, 2020)
12
13 # Using the object
14 print(my_car.display_info ())
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 11 / 49
12. Introduction to Object-Oriented Programming Creating and Using Classes
Explanation of Code
The __init__ method is a constructor that initializes the
object.
self refers to the current instance of the class.
The display_info() method returns a formatted string with
the car's details.
my_car is an instance of the Car class, initialized with brand,
model, and year.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 12 / 49
14. Encapsulation What is Encapsulation?
What is Encapsulation?
Encapsulation is one of the core principles of Object-Oriented
Programming (OOP).
It refers to the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit, i.e., a
class.
Encapsulation also restricts direct access to some of the object's
components, which is used to hide the internal representation of
the object.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 14 / 49
15. Encapsulation Private and Public Members
Private and Public Members
In Python, class attributes and methods are by default public.
You can make an attribute or method private by prexing it with
an underscore (`_` for protected and `__` for private).
Private members are not accessible directly outside the class,
which ensures that sensitive data is hidden from external access.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 15 / 49
16. Encapsulation Example of Encapsulation in Python
Encapsulation: Example I
Example of encapsulation in Python:
1 class BankAccount:
2 def __init__(self , owner , balance =0):
3 self.owner = owner
4 self.__balance = balance # Private attribute
5
6 def deposit(self , amount):
7 if amount 0:
8 self.__balance += amount
9 return self.__balance
10
11 def withdraw(self , amount):
12 if 0 amount = self.__balance:
13 self.__balance -= amount
14 return amount
15 else:
16 return Insufficient funds
17
18 def get_balance(self):
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 16 / 49
17. Encapsulation Example of Encapsulation in Python
Encapsulation: Example II
19 return self.__balance
20
21 # Create a BankAccount object
22 account = BankAccount(Alice, 1000)
23
24 # Using methods to access private attribute
25 account.deposit (500)
26 print(account.get_balance ()) # Output: 1500
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 17 / 49
18. Encapsulation Explanation of Code
Explanation of Code
The attribute __balance is private, meaning it cannot be
accessed directly from outside the class.
The methods deposit, withdraw, and get_balance are used
to modify and access the private attribute __balance.
This ensures that the balance cannot be modied directly, only
through predened methods, thus ensuring data security.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 18 / 49
19. Encapsulation Why Encapsulation?
Why Encapsulation?
Encapsulation helps in protecting the internal state of an object.
It promotes data integrity by restricting unauthorized or
unintended access.
Through encapsulation, the object's internal state is only
modiable via public methods, providing controlled access.
It simplies debugging and helps maintain clean code
architecture.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 19 / 49
21. Inheritance What is Inheritance?
What is Inheritance?
Inheritance is one of the core principles of Object-Oriented
Programming (OOP).
It allows a class (child class) to inherit attributes and methods
from another class (parent class).
This promotes code reuse and establishes a relationship between
dierent classes.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 21 / 49
22. Inheritance Types of Inheritance
Types of Inheritance
Single Inheritance: A child class inherits from a single parent
class.
Multiple Inheritance: A child class inherits from multiple
parent classes.
Multilevel Inheritance: A child class inherits from a parent
class, and another class can inherit from the child class.
Hierarchical Inheritance: Multiple child classes inherit from a
single parent class.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 22 / 49
23. Inheritance Example of Single Inheritance
Single Inheritance Example
1 # Parent class
2 class Animal:
3 def __init__(self , name):
4 self.name = name
5
6 def speak(self):
7 return f{self.name} makes a sound
8
9 # Child class inheriting from Animal
10 class Dog(Animal):
11 def speak(self):
12 return f{self.name} barks
13
14 #Creating objects of both classes
15 animal = Animal(Generic Animal)
16 dog = Dog(Buddy)
17
18 # Accessing methods
19 print(animal.speak ()) # Output: Generic Animal makes a sound
20 print(dog.speak()) # Output: Buddy barks
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 23 / 49
24. Inheritance Explanation of Code
Explanation of Code
The class Animal is the parent class with the method speak().
The class Dog is a child class that inherits from Animal and
overrides the speak() method.
Objects of both classes are created, and the speak() method is
called on each object, demonstrating polymorphism (method
overriding).
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 24 / 49
25. Inheritance Example of Multilevel Inheritance
Multilevel Inheritance Example I
Example of multilevel inheritance in Python:
1 # Parent class
2 class Vehicle:
3 def __init__(self , brand):
4 self.brand = brand
5
6 def info(self):
7 return fVehicle brand: {self.brand}
8
9 # Child class inheriting from Vehicle
10 class Car(Vehicle):
11 def __init__(self , brand , model):
12 super().__init__(brand)
13 self.model = model
14
15 def info(self):
16 return fCar brand: {self.brand}, model: {self.model}
17
18 # Another child class inheriting from Car
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 25 / 49
26. Inheritance Example of Multilevel Inheritance
Multilevel Inheritance Example II
19 class ElectricCar(Car):
20 def __init__(self , brand , model , battery_capacity):
21 super().__init__(brand , model)
22 self.battery_capacity = battery_capacity
23
24 def info(self):
25 return fElectric Car: {self.brand} {self.model},
Battery: {self.battery_capacity}kWh
26
27 # Creating an object of ElectricCar
28 my_ecar = ElectricCar(Tesla, Model S, 100)
29 print(my_ecar.info()) # Output: Electric Car: Tesla Model S,
Battery: 100kWh
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 26 / 49
27. Inheritance Explanation of Code
Explanation of Code
The Vehicle class is the parent class, Car is a child class, and
ElectricCar is a child class of Car.
The super() function is used to call the constructor of the
parent class.
Each class adds or overrides attributes and methods,
demonstrating multilevel inheritance.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 27 / 49
28. Inheritance Advantages of Inheritance
Advantages of Inheritance
Promotes code reusability by inheriting methods and attributes
from a parent class.
Establishes relationships between classes, making it easier to
maintain and understand the code.
Enables method overriding, allowing child classes to modify the
behavior of inherited methods.
Supports polymorphism, making it easier to work with dierent
classes through a common interface.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 28 / 49
30. Polymorphism What is Polymorphism?
What is Polymorphism?
Polymorphism is one of the key principles of Object-Oriented
Programming (OOP).
It refers to the ability of dierent classes to be treated as
instances of the same class through a common interface.
Polymorphism allows methods to be used interchangeably
between dierent types of objects, as long as they implement the
same method signature.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 30 / 49
31. Polymorphism Types of Polymorphism
Types of Polymorphism
Compile-time Polymorphism: Also called method
overloading, but Python does not support this directly.
Run-time Polymorphism: Achieved through method
overriding, where the child class modies the behavior of the
parent class's method.
Python also supports polymorphism through duck typing,
where the type or class of an object is less important than the
methods it denes.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 31 / 49
32. Polymorphism Polymorphism with Method Overriding
Method Overriding Example
Example of polymorphism with method overriding in Python:
1 # Parent class
2 class Animal:
3 def speak(self):
4 return Animal makes a sound
5
6 # Child class overriding speak method
7 class Dog(Animal):
8 def speak(self):
9 return Dog barks
10
11 class Cat(Animal):
12 def speak(self):
13 return Cat meows
14
15 # Polymorphism in action
16 animals = [Animal (), Dog(), Cat()]
17
18 for animal in animals:
19 print(animal.speak ()) # Output depends on the object type
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 32 / 49
33. Polymorphism Explanation of Code
Explanation of Code
The Animal class denes a general speak() method.
The Dog and Cat classes override the speak() method to
provide their specic implementations.
The same method speak() is called on dierent objects in the
animals list, but the behavior changes based on the object's
class.
This demonstrates run-time polymorphism, where the method
call is determined by the type of the object at runtime.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 33 / 49
34. Polymorphism Polymorphism through Duck Typing
Duck Typing Example I
Python allows polymorphism through duck typing. If an object
implements a required method, its type doesn't matter.
1 class Bird:
2 def fly(self):
3 return Bird flies
4
5 class Airplane:
6 def fly(self):
7 return Airplane flies
8
9 class Fish:
10 def swim(self):
11 return Fish swims
12
13 # Polymorphism using duck typing
14 def make_it_fly(entity):
15 print(entity.fly())
16
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 34 / 49
35. Polymorphism Polymorphism through Duck Typing
Duck Typing Example II
17 bird = Bird()
18 airplane = Airplane ()
19
20 make_it_fly(bird) # Output: Bird flies
21 make_it_fly(airplane) # Output: Airplane flies
22
23 # make_it_fly(Fish()) # This will raise an AttributeError as
Fish does not have fly method
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 35 / 49
36. Polymorphism Explanation of Duck Typing Code
Explanation of Duck Typing Code
Both Bird and Airplane classes have the fly() method, so
they can be passed to the make_it_fly function.
This is an example of duck typing: If it looks like a duck and
quacks like a duck, it's a duck.
The function does not care about the actual type of the object,
only whether it has the required method.
Attempting to pass an object without the fly() method (like
Fish) will raise an error.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 36 / 49
37. Polymorphism Advantages of Polymorphism
Advantages of Polymorphism
Allows for exible and reusable code by allowing the same
interface to be used for dierent underlying forms (data types).
Makes it easier to add new classes with minimal changes to
existing code.
Reduces the complexity of programs and enhances the
maintainability of the code.
Promotes code organization by allowing objects of dierent
types to be handled uniformly.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 37 / 49
39. Abstraction What is Abstraction?
What is Abstraction?
Abstraction is one of the core principles of Object-Oriented
Programming (OOP).
It refers to hiding the complex implementation details of an
object and exposing only the essential features.
Abstraction allows focusing on what an object does instead of
how it does it.
In Python, abstraction is typically achieved through abstract
classes and interfaces.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 39 / 49
40. Abstraction Abstract Classes in Python
Abstract Classes in Python
An abstract class in Python is a class that cannot be
instantiated and serves as a blueprint for other classes.
It can have abstract methods that must be implemented by
subclasses.
Abstract classes are implemented using the abc module in
Python.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 40 / 49
41. Abstraction Example of Abstract Class
Abstract Class Example I
Example of an abstract class in Python:
1 from abc import ABC , abstractmethod
2
3 # Abstract class
4 class Shape(ABC):
5 @abstractmethod
6 def area(self):
7 pass
8
9 @abstractmethod
10 def perimeter(self):
11 pass
12
13 # Concrete class inheriting from abstract class
14 class Rectangle(Shape):
15 def __init__(self , width , height):
16 self.width = width
17 self.height = height
18
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 41 / 49
42. Abstraction Example of Abstract Class
Abstract Class Example II
19 def area(self):
20 return self.width * self.height
21
22 def perimeter(self):
23 return 2 * (self.width + self.height)
24
25 # Creating an object of Rectangle
26 rect = Rectangle(5, 10)
27 print(fArea: {rect.area()}) # Output: Area: 50
28 print(fPerimeter: {rect.perimeter ()}) # Output:
Perimeter: 30
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 42 / 49
43. Abstraction Explanation of Abstract Class Example
Explanation of Code
The Shape class is an abstract class that denes two abstract
methods: area() and perimeter().
The Rectangle class inherits from Shape and provides concrete
implementations for the area() and perimeter() methods.
Abstract methods in the Shape class must be implemented in
the child class, otherwise, the child class cannot be instantiated.
This demonstrates how abstraction is achieved by hiding
unnecessary details and only exposing the interface for
calculating area and perimeter.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 43 / 49
44. Abstraction Use of Abstraction in Python
Use of Abstraction
Abstraction allows dening common interfaces for dierent
subclasses.
It improves code modularity and extensibility by separating the
what from the how.
It promotes code maintainability by providing a clear interface
and allowing changes to the internal implementation without
aecting the external code.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 44 / 49
45. Abstraction Real-World Example of Abstraction
Real-World Example of Abstraction I
Another real-world example of abstraction using abstract classes:
1 from abc import ABC , abstractmethod
2
3 # Abstract class
4 class Device(ABC):
5 @abstractmethod
6 def turn_on(self):
7 pass
8
9 @abstractmethod
10 def turn_off(self):
11 pass
12
13 # Concrete class 1
14 class TV(Device):
15 def turn_on(self):
16 print(TV is now ON)
17
18 def turn_off(self):
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 45 / 49
46. Abstraction Real-World Example of Abstraction
Real-World Example of Abstraction II
19 print(TV is now OFF)
20 # Concrete class 2
21 class Radio(Device):
22 def turn_on(self):
23 print(Radio is now ON)
24
25 def turn_off(self):
26 print(Radio is now OFF)
27 # Using abstraction
28 def use_device(device):
29 device.turn_on ()
30 device.turn_off ()
31 # Creating objects of TV and Radio
32 tv = TV()
33 radio = Radio()
34
35 use_device(tv) # Output: TV is now ON, TV is now OFF
36 use_device(radio) # Output: Radio is now ON, Radio is now
OFF
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 46 / 49
47. Abstraction Explanation of Real-World Example
Explanation of Real-World Example
The abstract class Device denes two abstract methods:
turn_on() and turn_off().
Both TV and Radio provide their specic implementations for
these methods.
The use_device function demonstrates abstraction by
operating on objects of both TV and Radio classes without
needing to know the internal details of each device.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 47 / 49
48. Abstraction Advantages of Abstraction
Advantages of Abstraction
Reduces complexity by hiding implementation details and
exposing only essential functionalities.
Promotes code reusability and reduces code duplication by
dening common interfaces for subclasses.
Helps in achieving a modular and maintainable codebase.
Facilitates exibility by allowing changes to internal
implementations without aecting other parts of the system.
Laltu Sardar (IAI, TCG Crest) Intro to Python Programming 48 / 49