Chapter 10: Object-Oriented Programming (OOP) in Python – Classes & Objects

Previous Chapter Table of Contents Next Chapter

1. OOP Concepts

Class and Object Relationship

Classes are blueprints, objects are instances

Class

A blueprint for creating objects

class Dog:
    pass

Object

An instance of a class

my_dog = Dog()

Attribute

Data associated with an object

my_dog.name = "Rover"

Method

Function associated with an object

def bark(self):
    print("Woof!")

2. Defining Classes

Basic Class Structure

class Car:
    # Class attribute (shared by all instances)
    wheels = 4
    
    # Constructor (initialize instance attributes)
    def __init__(self, brand, model):
        self.brand = brand  # Instance attribute
        self.model = model
    
    # Instance method
    def description(self):
        return f"{self.brand} {self.model}"

# Create objects
my_car = Car("Toyota", "Corolla")
print(my_car.description())  # Toyota Corolla

Exercise 1: Create a Book Class

Create a Book class with:

  1. Attributes: title, author, pages
  2. Method info() that returns a description
  3. Create an instance and call the method

3. Inheritance

Base (Parent) Class

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("Subclass must implement")

Derived (Child) Class

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

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

Usage

dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())  # Buddy says Woof!
print(cat.speak())  # Whiskers says Meow!

Exercise 2: Shape Inheritance

Create a base Shape class with:

  1. Method area() that raises NotImplementedError
  2. Derived classes Rectangle and Circle
  3. Implement area() in each subclass

4. Encapsulation

Private Attributes (Name Mangling)

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())  # 1500
# account.__balance  # Error: AttributeError

Python doesn't have truly private attributes, but name mangling (__attribute) makes them harder to access accidentally.

5. Polymorphism

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

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

def animal_sound(animal):
    print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Woof!
animal_sound(cat)  # Meow!

Exercise 3: Polymorphic Payment

Create payment classes that demonstrate polymorphism:

  1. Base class Payment with process() method
  2. Subclasses CreditCard, PayPal, BankTransfer
  3. Each implements process() differently
Previous Chapter Next Chapter