← Back to Python

All Topics

Advertisement

Learn/Python/Intermediate Python

Object-Oriented Programming

Topic: OOP

Advertisement

Introduction

Object-Oriented Programming (OOP) organizes code around objects that combine data and functionality.

Classes and Objects

class Dog:
    # Class attribute
    species = "Canis familiaris"
    
    # Constructor
    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age
    
    # Instance method
    def bark(self):
        return f"{self.name} says woof!"
    
    # String representation
    def __str__(self):
        return f"{self.name} is {self.age} years old"

# Create object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())

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"

Multiple Inheritance

class Flyable:
    def fly(self):
        return f"{self.name} is flying"

class Swimmable:
    def swim(self):
        return f"{self.name} is swimming"

class Duck(Animal, Flyable, Swimmable):
    pass

Practice Problems

  1. Create a BankAccount class with deposit/withdraw
  2. Design an inheritance hierarchy for shapes
  3. Implement str and repr methods
  4. Create a class with class and instance attributes
  5. Use multiple inheritance for a real scenario

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →