Showing posts with label Python OOP. Show all posts
Showing posts with label Python OOP. Show all posts

Monday, March 16, 2026

Lesson 13: Python Classes and Object-Oriented Programming | Coding Class Series

March 16, 2026 0



Lesson 13: Python Classes and Object-Oriented Programming (OOP) | Coding Class Series

Introduction

Welcome to Lesson 13!
In this lesson, we will learn about Object-Oriented Programming (OOP) in Python, including classes, objects, methods, and inheritance.
OOP helps you structure your code in a way that models real-world objects and makes programming more organized and reusable.


1. What is a Class?

A class is a blueprint for creating objects. It defines attributes (data) and methods (functions).

# Define a class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def bark(self):
        print(f"{self.name} says Woof!")

2. Creating Objects

An object is an instance of a class.

# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

print(dog1.name)  # Buddy
dog2.bark()       # Max says Woof!

3. The __init__ Method

  • __init__ is a constructor used to initialize objects.
  • self refers to the instance of the class.
class Cat:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def meow(self):
        print(f"{self.name}, the {self.color} cat, says Meow!")

4. Methods

Methods are functions inside classes that operate on objects.

class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.1416 * self.radius ** 2
    
    def perimeter(self):
        return 2 * 3.1416 * self.radius

c = Circle(5)
print(c.area())       # 78.54
print(c.perimeter())  # 31.416

5. Inheritance

Inheritance allows a class to inherit attributes and methods from another class.

class Animal:
    def speak(self):
        print("Some sound")

class Dog(Animal):
    def speak(self):
        print("Woof Woof")

class Cat(Animal):
    def speak(self):
        print("Meow Meow")

d = Dog()
c = Cat()
d.speak()  # Woof Woof
c.speak()  # Meow Meow

6. Encapsulation

Encapsulation hides data inside a class using private attributes.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private variable
    
    def deposit(self, amount):
        self.__balance += amount
    
    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # 1500

7. Polymorphism

Polymorphism allows objects of different classes to be used interchangeably.

class Bird:
    def speak(self):
        print("Tweet")

class Dog:
    def speak(self):
        print("Woof")

def make_speak(animal):
    animal.speak()

b = Bird()
d = Dog()
make_speak(b)  # Tweet
make_speak(d)  # Woof

8. Practice Exercises

  1. Create a class Student with attributes name, roll_no, marks. Write a method to calculate percentage.
  2. Create a class Vehicle and inherit it with Car and Bike. Add different methods to each.
  3. Implement encapsulation for a Library class where books is private.
  4. Write a program demonstrating polymorphism with two different classes.


Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

March 16, 2026 0



Lesson 9: Object-Oriented Programming (OOP) in Python | Coding Class Series

Introduction

Welcome to Lesson 9!
In this lesson, we will learn Object-Oriented Programming (OOP) in Python, which is a powerful way to structure code using classes and objects. OOP helps you write reusable, organized, and maintainable programs.


1. What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities.
Key concepts:

  • Class → Blueprint of an object
  • Object → Instance of a class
  • Attributes → Properties of an object
  • Methods → Functions of an object

2. Creating a Class and Object

Example:

class Person:
    def __init__(self, name, age):
        self.name = name  # Attribute
        self.age = age    # Attribute

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object
person1 = Person("Alice", 20)
person1.greet()  # Output: Hello, my name is Alice and I am 20 years old.

Explanation:

  • __init__ → Constructor method, runs automatically when object is created
  • self → Refers to the current object

3. Inheritance

Inheritance allows a class to reuse code from another class.

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def show_id(self):
        print(f"My student ID is {self.student_id}")

student1 = Student("Bob", 18, "S123")
student1.greet()      # Inherited method
student1.show_id()    # Own method

Benefits:

  • Reuse existing code
  • Create hierarchical relationships
  • Simplify complex programs

4. Encapsulation

Encapsulation is the concept of hiding private details of an object.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())  # Output: 1500

Note: Prefix __ to make an attribute private.


5. Polymorphism

Polymorphism allows methods with the same name to behave differently depending on the object.

class Dog:
    def speak(self):
        print("Woof!")

class Cat:
    def speak(self):
        print("Meow!")

animals = [Dog(), Cat()]
for animal in animals:
    animal.speak()
# Output: Woof! Meow!

6. Practice Exercises

  1. Create a class Car with attributes brand and year, and method display_info().
  2. Create a subclass ElectricCar that inherits from Car and adds battery_capacity.
  3. Create objects of both classes and call their methods.
  4. Make a class Account with private balance and methods deposit and withdraw.