Introduction to Object-Oriented Programming (OOP)
What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to
structure software in a way that models real-world entities. It emphasizes modularity, reusability, and
organization of code by grouping related variables (data) and functions (methods) together.
Objects
Objects are instances of classes. They represent real-world entities with state and behavior. For
example, a 'Car' object may have attributes like color and speed, and behaviors like drive() and
brake().
Classes
A class is a blueprint for creating objects. It defines a data structure and the functions that operate
on the data. For example:
class Car:
def __init__(self, color):
self.color = color
def drive(self):
print('Driving')
Data Abstraction
Data Abstraction means exposing only essential features while hiding the implementation details.
For example, when you use a TV remote, you interact with the interface without knowing the internal
workings.
Data Encapsulation
Encapsulation is the concept of wrapping data and the methods that operate on the data within one
unit. It restricts direct access to some of an object's components. Example:
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute
def get_balance(self):
return self.__balance
Inheritance
Inheritance allows a class to inherit properties and methods from another class. It promotes code
reuse. Example:
class Vehicle:
def move(self):
print('Moving')
class Car(Vehicle):
def honk(self):
print('Beep!')
Polymorphism
Polymorphism means the ability to take many forms. It allows methods to do different things based
on the object. Example:
class Dog:
def speak(self):
print('Bark')
class Cat:
def speak(self):
print('Meow')
def make_sound(animal):
animal.speak()
Dynamic Binding
Dynamic binding refers to the process of resolving method calls at runtime rather than compile-time.
It allows for more flexible and extensible code through polymorphism.