Object-Oriented Programming (OOP) in Python ๐

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code efficiently. Python supports OOP with features like encapsulation, inheritance, and polymorphism.
1๏ธโฃ Classes and Objects
What is a Class?
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the objectโs behavior.
What is an Object?
An object is an instance of a class. Multiple objects can be created from a single class.
2๏ธโฃ Defining a Class
๐ Use the class keyword to define a class.
class Car:
pass # Empty class (for now)
๐น Car is a class, but it doesn't do anything yet.
3๏ธโฃ Creating Objects (Instances of a Class)
๐ To create an object, call the class name like a function.
class Car:
pass
# Creating objects
car1 = Car()
car2 = Car()
print(type(car1)) # Output:
print(type(car2)) # Output:
๐น car1 and car2 are two separate objects of the Car class.
4๏ธโฃ Attributes and Methods
Attributes (Instance Variables)
๐ Attributes are variables that belong to an object. They define the state of an object.
class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand # Attribute
self.model = model # Attribute
self.year = year # Attribute
# Creating objects with attributes
car1 = Car("Toyota", "Camry", 2022)
car2 = Car("Honda", "Civic", 2021)
print(car1.brand) # Output: Toyota
print(car2.model) # Output: Civic
๐น __init__() is a constructor that initializes object attributes.
๐น self.brand, self.model, self.year are instance attributes.
Methods (Functions inside a Class)
๐ Methods define behaviors of an object.
class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
def display_info(self):
return f"{self.year} {self.brand} {self.model}"
# Creating an object
car1 = Car("Tesla", "Model S", 2023)
print(car1.display_info()) # Output: 2023 Tesla Model S
๐น display_info() is a method that returns car details.
๐น self allows access to object attributes inside methods.
5๏ธโฃ The self Keyword
๐ self represents the current instance of a class. It is used to access instance attributes and methods.
class Person:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# Creating an object
p1 = Person("Alice", 30)
print(p1.greet()) # Output: Hello, my name is Alice and I am 30 years old.
๐น self.name refers to the name attribute of the current object.
๐น Without self, Python wonโt know which object's attribute to access.
Date: 2025-03-22 00:00:00.000000