Introduction to Object-Oriented Programming (OOP) in Python
Introduction
Python is an object-oriented programming language.
OOP (Object-Oriented Programming) helps structure your code in a way that’s modular, reusable, and organized.
It revolves around two main concepts:
Classes – Blueprints for creating objects
Objects – Instances of classes that hold real data
1. Defining a Class
A class is a blueprint for objects.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
2. Creating Objects
Objects are instances of a class.
Example:
s1 = Student("Ravi", 20)
s2 = Student("Anita", 19)
s1.display()
s2.display()
Output:
Name: Ravi
Age: 20
Name: Anita
Age: 19
3. The __init__() Method
The __init__() method is called automatically when an object is created.
It’s used to initialize attributes (like name, age, etc.).
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Mahindra", "Model 3")
print(car1.brand, car1.model)
Output:
Reliance Model 3
4. Instance vs Class Variables
Example:
class Employee:
company = "TechCorp" # class variable
def __init__(self, name):
self.name = name # instance variable
e1 = Employee("Habbit2Code")
e2 = Employee("CodingClass")
print(e1.company, e1.name)
print(e2.company, e2.name)
Output:
TechCorp Habbit2Code
TechCorp CodingClass
5. Adding Methods to a Class
Methods are functions defined inside a class that operate on the data of that class.
class Calculator:
def add(self, a, b):
return a + b
calc = Calculator()
print("Sum =", calc.add(10, 5))
Output:
Sum = 15
6. The self Keyword
The self parameter refers to the current instance of the class.
It’s automatically passed when you call a method.
You don’t need to pass it explicitly.
7. Advantages of OOP
Reusability – Classes can be reused across programs
Modularity – Divide your program into logical sections
Flexibility – Easy to modify and extend
Real-world modeling – Represents entities like Student, Car, Employee, etc.
Challenge for You
Create a class Book with:
-
Attributes:
title,author,price -
Method:
display()to show book details
Then create two objects and display their details.
Summary:
OOP makes Python powerful and scalable.
With just classes and objects, you can model real-world entities efficiently.
In the next lesson, we’ll dive into OOP Concepts: Inheritance, Polymorphism, and Encapsulation.
.png)
.png)
Comments
Post a Comment