Module 2

Object-Oriented Programming in Python

20 mins read

Lesson 1: Object-Oriented Programming

1.1 Introduction to Classes & Objects

OOP organizes code into reusable classes. In Python, classes define attributes and methods initialized via `__init__` constructors.

PYTHON
# Defining a class in Python
class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    
    def display_info(self):
        print(f"Car: {self.brand} {self.model}")

my_car = Car("Toyota", "Camry")
my_car.display_info() # Output: Car: Toyota Camry
1.2 Inheritance & Polymorphism

Inheritance allows child classes to derive properties from superclasses, while polymorphism lets subclasses override parent methods.

PYTHON
class Animal:
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Bark"

def make_sound(animal):
    print(animal.sound())

make_sound(Dog()) # Output: Bark