[Python OOP] 8. Practical Examples and Projects

09 Nov 2023 By Code Bricks

8. Practical Examples and Projects

Putting theory into practice is an essential part of learning Object-Oriented Programming (OOP) in Python. Here we will outline a series of practical examples and projects that reinforce OOP concepts.

8.1 Building a Command-Line Application

Command-line applications are great for understanding the flow of an OOP program since they involve clear sequences of actions and user interactions.

Example Project: Todo List CLI

You can create a command-line application that allows a user to manage their tasks.

class TodoList:
    def __init__(self):
        self.todos = []

    def add(self, task):
        self.todos.append(task)
    
    def list(self):
        for idx, task in enumerate(self.todos, 1):
            print(f"{idx}. {task}")

    def remove(self, idx):
        try:
            self.todos.pop(idx - 1)
        except IndexError:
            print("Task not found.")

class CLI:
    def __init__(self):
        self.todo_list = TodoList()

    def run(self):
        while True:
            command = input("Enter command (add, list, remove, exit): ")
            if command == "exit":
                break
            elif command == "add":
                task = input("Enter the task: ")
                self.todo_list.add(task)
            elif command == "list":
                self.todo_list.list()
            elif command == "remove":
                idx = int(input("Enter task number to remove: "))
                self.todo_list.remove(idx)
            else:
                print("Unknown command!")

if __name__ == "__main__":
    cli = CLI()
    cli.run()

8.2 Developing a Simple Web Application with Flask

Web applications are an excellent opportunity to apply OOP for handling web requests, structuring data, and rendering responses.

Example Project: Book Library Web App

You can build a simple web application with Flask that allows users to add and view books in a library.

from flask import Flask, request, render_template

app = Flask(__name__)
library = {}

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        title = request.form['title']
        author = request.form['author']
        library[title] = Book(title, author)
    return render_template('index.html', library=library)

if __name__ == "__main__":
    app.run(debug=True)

8.3 Creating a Game with Pygame

Game development is another fun way to learn OOP. You can manage game entities, handle events, and create interactions.

Example Project: Simple Pong Game

Design a basic Pong game using Pygame, where you control paddles using keyboard inputs.

import pygame

pygame.init()

class Paddle:
    # Paddle class code here

class Ball:
    # Ball class code here

def main():
    # Game initialization code
    # Game loop with event handling and drawing
    
if __name__ == "__main__":
    main()

These practical examples give you hands-on experience with Python’s OOP features, allowing you to build your own projects with a strong understanding of the concepts discussed.