DSPython Logo DSPython

Object-Oriented Programming (OOP)

Learn to structure your code using Classes and Objects.

Python ADV Intermediate 30 min

๐Ÿ—๏ธ Introduction: The "Blueprint" Analogy

Imagine you are an architect designing a house. You draw a Blueprint (Plan). This blueprint is NOT a house; you cannot live in it. But using this one blueprint, you can build thousands of real houses.

In Python:
1. Class: The Blueprint (The design).
2. Object: The Real House (The actual thing built from the design).
3. Attributes: Details like "Color", "Number of Rooms" (Data).
4. Methods: Actions like "Open Door", "Turn on Lights" (Functions).

This style of coding is called Object-Oriented Programming (OOP). It helps organize code by grouping data and behavior together.

๐Ÿ“ฆ Topic 1: Defining Classes & Objects

To create a class, we use the class keyword. By convention, class names use CapitalizedWords (PascalCase).

๐Ÿ“ Syntax:

class Dog:
    # Attributes and methods go here
    # Indentation is key!

๐Ÿ’ป Example: A Simple Dog Class

# 1. Define the Blueprint (Class)
class Dog:
species = "Canine"
def bark(self):
print("Woof! Woof!")

# 2. Build the Houses (Objects)
dog1 = Dog() ย # First dog object
dog2 = Dog() ย # Second dog object

# 3. Use them
print(dog1.species) ย # Output: Canine
dog2.bark() ย  ย  ย  ย  ย # Output: Woof! Woof!

๐Ÿ’ก What is 'self'?

self represents the instance of the class. When you have 100 houses, and you say "Paint the door red", self tells the painter which specific house's door to paint.

๐Ÿ”ง Topic 2: The __init__() Constructor

Usually, when you create an object, you want to give it some starting values (like a name or age). The __init__ function is called automatically every time the class is being used to create a new object.

๐Ÿ’ป Example: Customized Objects

class Person:
# The Constructor
def __init__(self, name, age):
self.name = name ย # Saves 'name' to the object
self.age = age ย  ย # Saves 'age' to the object

# Creating objects with different data
p1 = Person("Vinay", 25)
p2 = Person("Priya", 22)

print(p1.name) ย # Output: Vinay
print(p2.age) ย  # Output: 22

โš™๏ธ Topic 3: Methods (Object Actions)

Methods are functions that belong to an object. They can perform operations using the object's data (attributes).

๐Ÿ’ป Example: Bank Account

class BankAccount:
def __init__(self, balance=0):
self.balance = balance

def deposit(self, amount):
self.balance += amount
print(f"Added ${amount}. Balance: ${self.balance}")

def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. Balance: ${self.balance}")
else:
print("Insufficient Funds!")

# Usage
my_account = BankAccount(100)
my_account.deposit(50) ย  ย # Balance: 150
my_account.withdraw(200) ย  # Insufficient Funds

๐Ÿ‘จโ€๐Ÿ‘งโ€๐Ÿ‘ฆ Topic 4: Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Parent Class (Base Class): The class being inherited from (e.g., Animal).
Child Class (Derived Class): The class that inherits (e.g., Dog).

๐Ÿ’ป Example: Animal Kingdom

class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Some sound")

# Child Class inherits from Animal
class Dog(Animal):
def speak(self): ย # Overriding the parent method
print(f"{self.name} says Woof!")

class Cat(Animal):
def speak(self):
print(f"{self.name} says Meow!")

d
= Dog("Buddy")
c
= Cat("Kitty")
d
.speak() ย # Buddy says Woof!
c
.speak() ย # Kitty says Meow!

๐Ÿ“š Module Summary

  • Class: The Blueprint/Template.
  • Object: The actual instance created from the class.
  • __init__: The constructor that runs when object is created.
  • self: Refers to the specific object being used.
  • Inheritance: Sharing logic between Parent and Child classes.

๐Ÿค” Interview Q&A

Tap on the questions below to reveal the answers.

self represents the instance of the class. It allows the code to differentiate between different objects of the same class. For example, if you have two Dog objects, self.name ensures you get the name of the specific dog you asked for.

Yes. Python allows a child class to inherit from multiple parent classes. Example: class Child(Parent1, Parent2):. This is powerful but can be complex (Diamond Problem).

No. It is not mandatory. If you don't write one, Python uses a default empty constructor. However, you almost always use it to set up initial values for your object.

Encapsulation is the bundling of data (attributes) and methods that operate on that data into a single unit (class). It also involves restricting direct access to some of an object's components (using private variables like __balance).