๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 4 ยท Fundamentals

Object-Oriented Programming

Understand classes, objects, inheritance, and encapsulation in Python.

Classes and Objects

OOP is a paradigm based on "objects", which can contain data (attributes) and code (methods).

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        print(f"{self.name} says Woof!")

my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()

Inheritance

Classes can inherit from other classes to reuse and extend code.

class Animal:
    def speak(self):
        pass

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

my_cat = Cat()
my_cat.speak()

Encapsulation and Properties

Control access to internal state using private attributes (prefixed with _ or __) and properties.

class Account:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

acc = Account(1000)
print(acc.balance)

โœ… Practice (20 minutes)

  • Create a Car class with attributes make, model, and year.
  • Add a drive() method that prints "The [make] [model] is driving."
  • Create an ElectricCar class that inherits from Car and adds a battery_size attribute.
  • Override the drive() method in ElectricCar to include battery information.