Object-Oriented Programming (OOP) is a powerful paradigm where you design your applications using classes and objects. Classes serve as blueprints, and objects are instances of those blueprints.
π Essential for building structured, reusable, and scalable code in larger projects.
πΉ 1. What is OOP?
OOP organizes code around objects rather than just functions and data. It focuses on concepts like encapsulation, inheritance, and polymorphism to make complex systems easier to manage.
πΉ 2. Class vs. Object
β’ Class: A blueprint or a template for creating objects. It defines the properties (attributes) and behaviors (methods) that all objects of that type will have.
β’ Object: An instance of a class. It's a real-world entity created from the class blueprint.
Example:
Class = Car, Object = "My blue Honda Civic"πΉ 3. Defining a Class
We use the
class keyword to define a new class. Class names typically start with an uppercase letter.Syntax:
class ClassName:
# attributes (variables)
# methods (functions)
Example:
class Dog:
species = "Canis familiaris" # Class attribute
def __init__(self, name, age): # Constructor method
self.name = name # Instance attribute
self.age = age # Instance attribute
πΉ 4. Creating an Object (Instantiating a Class)
To create an object from a class, you call the class name as if it were a function. This process is called instantiation.
Example:
my_dog = Dog("Buddy", 3) # Creating an object 'my_dog'
your_dog = Dog("Lucy", 5) # Creating another object 'your_dog'πΉ 5. Object Attributes & Methods
β’ Attributes: Variables that belong to an object (e.g.,
name, age). Accessed using dot notation: object.attribute.β’ Methods: Functions that belong to an object (e.g.,
bark()). Defined inside the class and always take self as their first parameter.Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self): # A method
print(f"{self.name} says Woof!")
my_dog = Dog("Rex")
print(my_dog.name) # Access attribute
my_dog.bark() # Call method
Output:
RexRex says Woof!π― Today's Goal(What you should do)
βοΈ Understand the concept of classes as blueprints and objects as instances
βοΈ Define a simple class with attributes and methods
βοΈ Create objects from a class