0% found this document useful (0 votes)
6 views16 pages

What Is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses 'objects' to bundle data and behavior, allowing for modeling of real-world entities through classes and objects. The four pillars of OOP include encapsulation, inheritance, polymorphism, and abstraction, each serving to enhance code organization, security, and reusability. Encapsulation protects data, inheritance promotes code reuse, polymorphism allows for method flexibility, and abstraction simplifies interface usage while hiding complex details.

Uploaded by

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

What Is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses 'objects' to bundle data and behavior, allowing for modeling of real-world entities through classes and objects. The four pillars of OOP include encapsulation, inheritance, polymorphism, and abstraction, each serving to enhance code organization, security, and reusability. Encapsulation protects data, inheritance promotes code reuse, polymorphism allows for method flexibility, and abstraction simplifies interface usage while hiding complex details.

Uploaded by

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

What is OOP?

What is OOP?
• Object-Oriented Programming (OOP) is a programming paradigm
based on the concept of “objects”, which bundle data and behavior
together.
• Instead of writing procedures or functions, OOP helps you model real-
world entities using classes and objects.
• Class
• A class is a blueprint for creating objects. It defines attributes (data)
and methods (functions) that describe the behavior of the objects.
• Object
• An object is an instance of a class. It is a real-world entity created
from the class, with its own unique data.
• 4 Pillars of OOP in Python
• 1. EncapsulationHides internal state and protects data using
access control
• 2. Inheritance One class can inherit attributes and methods
from another
• 3. Polymorphism Different classes can define methods
with the same name but different behavior
• 4. Abstraction Hides complex implementation and shows
only essential features
Example;
• class Car: • my_car = Car("Toyota")
• def __init__(self, brand): • my_car.drive()
• self.brand = brand • # Output: Toyota is driving.
• def drive(self):
• print(f"{self.brand} is
driving.")
Book class with two objects
• class Book: • # Create two book objects
• def __init__(self, title, author, • book1 = Book("The Great
pages): Gatsby", "F. Scott Fitzgerald",
• self.title = title 180)
• self.author = author • book2 = Book("1984", "George
• self.pages = pages Orwell", 328)

• def display_info(self): • # Call display_info() on each


• print(f"'{self.title}' by • book1.display_info()
{self.author}, {self.pages} pages.") • book2.display_info()
What is Encapsulation?
• Encapsulation means hiding the internal state of an object and only
exposing a controlled interface. It's a way to protect data from being
modified directly from outside the class.
• In simple terms:
• You bundle data and methods that work on that data inside a class, and
you restrict direct access to some of the object’s attributes.
• Why Use Encapsulation?
• To prevent accidental changes to critical data.
• To provide controlled access to the data using getter/setter methods.
• To make code easier to maintain and more secure.
• Python doesn’t have true private variables like some other languages
(e.g., Java), but it does have conventions and tricks to make attributes
“private”.
• 🔸 Public, Protected, Private

Access Type Syntax Can be accessed from outside?

Public name Yes


Protected _name Yes (but discouraged)
Private __name 🚫 No (name mangled)
• class BankAccount:
• def get_balance(self):
• def __init__(self, owner, balance):
• self.owner = owner • return self.__balance
• self.__balance = balance # Private
attribute
• account = BankAccount("Alice",
• def deposit(self, amount): 1000)
• if amount > 0:
• account.deposit(500) #
• self.__balance += amount
Deposited $500
• print(f"Deposited ${amount}")
• account.withdraw(200) #
• else:
Withdrew $200
• print("Amount must be positive")
• print(account.get_balance()) # 1300
• def withdraw(self, amount):
• if amount <= self.__balance: • # Trying to access private variable
• self.__balance -= amount
directly:
• print(f"Withdrew ${amount}") • print(account.__balance) # ❌
• else:
AttributeError
• print("Insufficient balance")
What is Inheritance?
• Inheritance lets a class (called a child or subclass) inherit the
properties and methods of another class (called a parent or superclass).
• Think of it like real life:
• A Dog is an Animal. So Dog can inherit all the features of Animal, and
add some dog-specific ones too.
• Why Use Inheritance?
• Code reuse – don't repeat code
• Organize similar types of classes
• Extend existing functionality
• Basic Syntax • # Child class
• • class Dog(Animal):
class ParentClass: • def speak(self):
• # code • print(f"{self.name} says Woof!")
• class ChildClass(ParentClass): • # Another child class
• # inherits from ParentClass • class Cat(Animal):
• Example • def speak(self):
• # Parent class • print(f"{self.name} says
• class Animal: Meow.")
• def __init__(self, name): • a = Animal("Creature")
• self.name = name • d = Dog("Buddy")
• c = Cat("Whiskers")
• def speak(self): • a.speak() # Creature makes a sound.
• print(f"{self.name} makes a • d.speak() # Buddy says Woof!
sound.")
• c.speak() # Whiskers says Meow.
Overriding Methods
• The speak() method is • class Dog(Animal):
overridden in the child classes • def speak(self):
(Dog and Cat). You can still call
the parent’s version using super() • super().speak() # calls the
if needed. parent class method
• print(f"{self.name} also
says Woof!")
What is Abstraction?
• Why Use Abstraction?
• Abstraction means hiding the
internal details and showing only
• Keeps your code clean and focused
the essential features of an
object.
• Abstraction = Show what is • Helps with security (by hiding
necessary, hide how it works. internal logic)

• It’s like using a TV remote —


you press buttons to control it, • Makes it easier to update or change
but you don’t need to know how how something works without
affecting the rest of the code
the circuits inside work.
How to Implement Abstraction in Python
• # Concrete class
• Python uses the abc module • class Dog(Animal):
(Abstract Base Class) to create • def sound(self):
abstract classes and methods.
• return "Bark!"
• from abc import ABC, • class Cat(Animal):
abstractmethod
• def sound(self):
# Abstract class • return "Meow!"
• class Animal(ABC):
• @abstractmethod • d = Dog()
• def sound(self): • c = Cat()
• pass # No implementation • print(d.sound()) # Bark!
here • print(c.sound()) # Meow!
What is Polymorphism?
• Polymorphism means "many • class Dog:
forms". • def speak(self):
• In Python OOP, polymorphism • return "Woof!"
allows different classes to have
methods with the same name, but
different behavior. • class Cat:
• You can call the same method on • def speak(self):
different objects, and they will • return "Meow!"
respond in their own way.
• def make_sound(animal): • Even though we're calling the
• print(animal.speak()) same method speak(), the output
depends on the object type (Dog
or Cat). That's polymorphism in
• d = Dog() action!
• c = Cat()

• make_sound(d) # Woof!
• make_sound(c) # Meow!
Types of Polymorphism in Python
• Method Overriding Same • print(5 + 10) # 15 (int
method name in child class addition)
overrides parent method • print("Hello " + "World") #
• Operator Overloading Same Hello World (string
operator does different things concatenation)
depending on types (e.g. + works • Here, + works differently
for both numbers and strings) depending on the data type →
that's polymorphism too.

You might also like