Menu

Classes and Objects

Introduction

Object-oriented programming (OOP) is a paradigm that organizes code into classes (blueprints) and objects (instances). Python is a fully object-oriented language — in fact, everything in Python is an object.

Creating classes

class Dog:
    # Class variable (shared by all instances)
    species = "Canis familiaris"
    
    def __init__(self, name, age):
        # Instance variables (unique to each instance)
        self.name = name
        self.age = age
    
    def bark(self):
        return f"{self.name} says Woof!"
    
    def __str__(self):
        return f"{self.name}, age {self.age}"
    
    def __repr__(self):
        return f"Dog('{self.name}', {self.age})"

# Creating objects
my_dog = Dog("Rex", 3)
print(my_dog.bark())   # "Rex says Woof!"
print(my_dog)          # "Rex, age 3" (uses __str__)
print(my_dog.species)  # "Canis familiaris"

Inheritance

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError

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

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

animals = [Cat("Whiskers"), Dog("Buddy")]
for animal in animals:
    print(animal.speak())  # Polymorphism in action!

Assignment

  1. Read about Python classes in the official tutorial.
  2. Create a BankAccount class with deposit, withdraw, and balance methods.
  3. Create a SavingsAccount that inherits from BankAccount and adds an interest rate.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!