Introduction to OOP
•Object-Oriented Programming (OOP) is a
paradigm based on the concept of objects.
• Key Features:
• ✔ Encapsulation
• ✔ Inheritance
• ✔ Polymorphism
• ✔ Abstraction
3.
Why Use OOP?
•• Helps in structuring complex programs
efficiently.
• • Encourages reusability through inheritance.
• • Provides better data security with
encapsulation.
• • Supports polymorphism for flexible
programming.
4.
Classes and Objects
•✔ A **class** is a blueprint for creating objects.
• ✔ An **object** is an instance of a class.
• Example:
• ```python
• class Car:
• def __init__(self, brand, model):
• self.brand = brand
• self.model = model
• car1 = Car('Toyota', 'Camry')
• print(car1.brand) # Output: Toyota
• ```
Inheritance
• ✔ Inheritanceallows a class to use properties of another
class.
• ✔ Helps in code reusability.
• Example:
• ```python
• class Animal:
• def speak(self):
• print('Animal speaks')
• class Dog(Animal):
• def speak(self):
• print('Dog barks')
• d = Dog()
• d.speak() # Output: Dog barks
• ```
7.
Polymorphism
• ✔ **Polymorphism**allows different classes to use the same
method in different ways.
• Example:
• ```python
• class Bird:
• def fly(self):
• print('Some birds can fly')
• class Sparrow(Bird):
• def fly(self):
• print('Sparrow can fly')
• obj = Sparrow()
• obj.fly() # Output: Sparrow can fly
• ```
8.
Creating Classes andObjects
• ✔ **Instance Variables vs Class Variables**
• ✔ **Constructor (`__init__` method)**
• Example:
• ```python
• class Student:
• college = 'XYZ University' # Class variable
• def __init__(self, name):
• self.name = name # Instance variable
• s1 = Student('Rahul')
• print(s1.college) # Output: XYZ University
• ```
9.
Single Inheritance
• ✔A child class inherits properties from a single parent class.
• Example:
• ```python
• class Parent:
• def func1(self):
• print('Parent function')
• class Child(Parent):
• def func2(self):
• print('Child function')
• obj = Child()
• obj.func1() # Output: Parent function
• ```
10.
Multiple Inheritance
• ✔A class can inherit from more than one parent class.
• Example:
• ```python
• class Father:
• def skill(self):
• print('Father is good at driving')
• class Mother:
• def skill(self):
• print('Mother is good at cooking')
• class Child(Father, Mother):
• pass
• c = Child()
• c.skill() # Output: Father is good at driving (Method Resolution Order applies)
• ```
Conclusion & Summary
•✔ OOP makes programming **modular,
reusable, and organized**.
• ✔ Key concepts: **Encapsulation, Inheritance,
Polymorphism**.
• ✔ Different types of **inheritance** for
different scenarios.
• ✔ Practice writing Python OOP code!