Object-Oriented Programming in Python – A Beginner’s Guide with Real Example

Shaik SameerShaik Sameer
5 min read

Object-Oriented Programming (OOP) is a powerful way to structure and organize your Python code—especially when building real-world applications like booking systems, online stores, or management tools. In this guide, you'll learn the core principles of OOP in Python through simple, clean examples and relatable scenarios. Whether you're a beginner or someone looking to solidify your OOP understanding, this article will help you grasp concepts like classes, objects, methods, inheritance, and encapsulation without the fluff. Let’s make OOP practical, not just theoretical.

Object-Oriented Programming (OOP) in Python, written in a human, beginner-friendly tone, with real-world practical examples and structured in Markdown format.


🧠 Understanding OOP in Python — A Beginner’s Guide with Real Examples

Object-Oriented Programming (OOP) is one of the most important concepts in Python. If you’re building anything beyond a basic script—like a hotel booking system, an e-commerce platform, or a ride-hailing app—learning OOP is a game-changer.

This guide will walk you through OOP in Python using clear explanations and a real-world scenario—no confusing computer science jargon, and no abstract "Animal-Dog-Cat" examples.


🧱 What is OOP and Why Should You Care?

Object-Oriented Programming helps you organize your code into reusable pieces called objects. Think of objects like mini-programs that have both:

  • Data (attributes)

  • Actions (methods)

This makes your code:

  • Cleaner and modular

  • Easier to manage

  • Scalable for real projects


🗂 Topics We’ll Cover

  1. What is a Class and Object?

  2. The __init__() Constructor

  3. Instance Variables vs Class Variables

  4. Writing Methods (Actions)

  5. Inheritance

  6. Encapsulation

  7. Real Example: Hotel Booking System


1. 🎭 Class and Object – The Blueprint and the Real Thing

A class is a blueprint. An object is a real-world item created from that blueprint.

🔧 Example: Representing a Hotel Room

class Room:
    def __init__(self, number, room_type):
        self.number = number
        self.room_type = room_type
        self.is_booked = False

# Creating objects
room1 = Room(101, "Deluxe")
room2 = Room(102, "Standard")

print(room1.number)  # 101
print(room2.room_type)  # Standard

2. __init__() – The Constructor Method

The __init__() method in Python is a special function that's automatically called whenever you create a new object from a class. It’s used to initialize the object’s data (also called attributes). Think of it like setting up the initial state of an object—like giving a hotel room its number and type the moment it’s created.

class Customer:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone

c1 = Customer("Amit", "9876543210")
print(c1.name)  # Amit

Think of __init__() as a way to give your object a starting state.


3. Instance Variables vs Class Variables

  • Instance variables are unique to each object. They store information that’s specific to that one instance.

  • Class variables are shared among all objects created from the class. They're great for keeping common data—like a hotel name that applies to all rooms.

💡 Example: All rooms belong to the same hotel

class Room:
    hotel_name = "The Blue Orchid"  # Class variable

    def __init__(self, number, room_type):
        self.number = number          # Instance variable
        self.room_type = room_type
room1 = Room(201, "Suite")
room2 = Room(202, "Deluxe")

print(room1.hotel_name)  # The Blue Orchid
print(room2.hotel_name)  # The Blue Orchid

4. Methods – Defining Object Behavior

Methods are functions inside a class that define what an object can do.

Methods are functions written inside a class that define what actions an object can perform. For example, a Room object might have a book() method to mark it as reserved. These methods allow objects to act on their own data, making your code feel more natural and organized.

class Room:
    def __init__(self, number):
        self.number = number
        self.is_booked = False

    def book(self):
        if not self.is_booked:
            self.is_booked = True
            print(f"Room {self.number} has been booked.")
        else:
            print(f"Room {self.number} is already booked.")

room1 = Room(301)
room1.book()  # ✅ Room 301 has been booked.
room1.book()  # ⚠️ Room 301 is already booked.

5. Inheritance – Reusing Code Like a Pro

Inheritance lets you create a new class from an existing one, inheriting all its methods and attributes. This is useful when you have a base structure (like a User) and want to build specialized versions of it (like Customer or Admin) without repeating code.

🛎️ Example: A Manager is a special kind of User

class User:
    def __init__(self, name):
        self.name = name

class Manager(User):  # Inherits from User
    def view_reports(self):
        print(f"{self.name} is viewing reports.")

mgr = Manager("Neha")
mgr.view_reports()  # Neha is viewing reports.

This keeps your code DRY (Don't Repeat Yourself).


6. Encapsulation – Protecting Your Data

Encapsulation is the practice of hiding internal details of an object and only exposing what’s necessary. In Python, you can protect data by making variables private (using __ prefix). This ensures that sensitive information, like a bank account balance, can't be modified directly from outside the class.

Example: Bank Account Balance

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private variable

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())  # 1500

# print(acc.__balance)  ❌ This will raise an error

Use __ to make variables private, so they can’t be accessed directly.


Real-World Example: Simple Hotel Booking System

Let’s tie everything together.

class Room:
    def __init__(self, number, room_type):
        self.number = number
        self.room_type = room_type
        self.is_booked = False

    def book(self):
        if not self.is_booked:
            self.is_booked = True
            print(f"Room {self.number} booked successfully.")
        else:
            print(f"Room {self.number} is already booked.")

    def status(self):
        return "Booked" if self.is_booked else "Available"

class Hotel:
    def __init__(self, name):
        self.name = name
        self.rooms = []

    def add_room(self, number, room_type):
        new_room = Room(number, room_type)
        self.rooms.append(new_room)

    def show_rooms(self):
        print(f"Rooms in {self.name}:")
        for room in self.rooms:
            print(f"Room {room.number} ({room.room_type}): {room.status()}")

# Using the classes
hotel = Hotel("Lakeview Resort")
hotel.add_room(101, "Deluxe")
hotel.add_room(102, "Suite")

hotel.show_rooms()
hotel.rooms[0].book()
hotel.show_rooms()

Output:

Rooms in Lakeview Resort:
Room 101 (Deluxe): Available
Room 102 (Suite): Available
Room 101 booked successfully.
Rooms in Lakeview Resort:
Room 101 (Deluxe): Booked
Room 102 (Suite): Available

✅ Key Takeaways

  • Classes group data and behavior together.

  • Objects are real-world instances of classes.

  • Use __init__() to set initial values.

  • Keep common values as class variables.

  • Use methods to define actions.

  • Inherit to reuse and extend existing code.

  • Encapsulate to protect sensitive data.


Final Words

Object-Oriented Programming is not just a concept—it’s a powerful way to think and structure your code. With OOP, your Python projects will be easier to build, extend, and maintain.

Whether you're making a hotel app, e-commerce platform, or inventory system, OOP will help you write professional, readable, and modular code.

0
Subscribe to my newsletter

Read articles from Shaik Sameer directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shaik Sameer
Shaik Sameer