Python: Object-Oriented Programming Basics

Introduction

So far, you’ve worked with variables, functions, and data structures. These are great for small programs, but as projects grow, you need a way to organize code more effectively. That’s where Object-Oriented Programming (OOP) comes in.

OOP lets you model real-world entities as classes and objects, making your programs cleaner, reusable, and scalable.

 

What Are Classes and Objects?

  • A class is a blueprint for creating objects.
  • An object is an instance of a class, with its own data and behaviour.

 

Example:

Code

class Dog:

    def __init__(self, name):

        self.name = name

 

    def bark(self):

        print(f"{self.name} says woof!")

 

my_dog = Dog("Buddy")

my_dog.bark()

  

Output:

Buddy says woof!

Here, Dog is the class, and my_dog is an object created from it.

  

The __init__ Method

The __init__ method is a special function that runs when you create an object. It initializes attributes.

Code:

class Car:

    def __init__(self, brand, year):

        self.brand = brand

        self.year = year

 

car1 = Car("Toyota", 2020)

print(car1.brand, car1.year)


Output:

Toyota 2020

 

Methods in Classes

Methods are functions defined inside a class that operate on its data.

Code:

class Calculator:

    def add(self, a, b):

        return a + b

 

calc = Calculator()

print(calc.add(5, 3)) 

 

Output: 8

Methods make objects interactive and useful.


Step 4: Inheritance

Inheritance allows one class to use features of another, promoting code reuse.

Code:

# Base class

class Animal:

    def speak(self):

        print("This animal makes a sound.")

 

    def eat(self):   # Inherited method (not overridden in Dog)

        print("This animal eats food.")

 

# Derived class

class Dog(Animal):

    # Overriding the speak() method

    def speak(self):

        print("The dog barks.")

 

# Create object of Dog

dog = Dog()

 

# Call overridden method

dog.speak()   # Output: The dog barks.

 

# Call inherited method (not overridden, comes from Animal)

dog.eat()     # Output: This animal eats food.

 

 Output:

The dog barks.

This animal eats food.


  •  Overridden method: Dog.speak() replaces Animal.speak() with its own implementation.
  • Inherited method: Dog.eat() is not defined in Dog, so it uses the Animal.eat() method directly.

This way, you see method overriding (custom behaviour in subclass) and method inheritance (reusing base class behaviour) side by side.

  

Step 5: Encapsulation

Encapsulation means hiding the internal representation of data and exposing it only through controlled interfaces (methods or properties).

Code:

class BankAccount:

    def __init__(self, balance):

        self.__balance = balance   # private

 

    def deposit(self, amount):

        self.__balance += amount

 

    def get_balance(self):

        return self.__balance

 

account = BankAccount(100)

account.deposit(50)

print(account.get_balance())        # works

print(account.__balance)            # AttributeError

 

Output:

150

Traceback (most recent call last):

  File "C:\Users\DES\Thonny\EML\tutorial.py", line 14, in <module>

    print(account.__balance)            #  AttributeError

AttributeError: 'BankAccount' object has no attribute '__balance'. Did you mean: 'get_balance'?


This hides internal details and provides controlled access.

 

Step 6: Polymorphism

Polymorphism means different classes can define the same method but behave differently.

Code:

class Cat:

    def speak(self):

        print("Meow")

 

class Dog:

    def speak(self):

        print("Woof")

 

for animal in [Cat(), Dog()]:

    animal.speak()

 

Output:

Meow

Woof


Same method name, different behaviours.

 

Mini Exercise

Try this challenge:

  1. Create a class Book with attributes title and author.
  2. Add a method describe() that prints "Title by Author".
  3. Create two book objects and call describe() on each.

 

Hint:

Code:

class Book:

    def __init__(self, title, author):

        self.title = title

        self.author = author

 

    def describe(self):

        print(f"{self.title} by {self.author}")

 

book1 = Book("Python Basics", "Deepak Sharma")

book2 = Book("Learning OOP", "Alice")

 

book1.describe()

book2.describe()

 

Conclusion

In this tutorial, you learned how to:

  • Define classes and create objects
  • Use the __init__ method to initialize attributes
  • Write methods inside classes
  • Apply inheritance, encapsulation, and polymorphism

 

OOP is the architecture of larger Python programs. It helps you design systems that are modular, reusable, and closer to real-world thinking.