OOP Part 2: Classes and Objects

By now, you know that Object-Oriented Programming is a way of structuring code by bundling related data and behaviour inside objects.

In this part, you'll get to:

  1. Learn exactly what a class is
  2. See a complete, more complex example
  3. Try your hand at creating your own very first class in a GPT assisted exercise

Let's begin by figuring out what a class really is.

1. What Is a Class?

The Explanation

Everything In Python Is Already A Class

When you run this:

You're not just storing a number in x. What you're actually doing is creating an object of Python's built-in int class.

The output: <class 'int'> Tells us that x is an instance of the int class.

What does Instance mean?
An instance is a specific object created from a class.
To instantiate means to create an instance.

Classes Are Already Everywhere In Python

For example, the int class defines how integers behave:

  • They store numeric values
  • They can be used with operators like +, -, *, /
  • They have methods like bit_length() and to_bytes_()

Similarly, the str class defines how strings work:

  • They store text
  • They have built-in methods like .upper() and .replace()

Since everything in Python is built using classes, we can define our own classes to create new types of objects.

Just like Python’s built-in int class defines how numbers behave, we can create a Book class to define how we want our representations of books to behave. This class will allow us to store book details and define actions like displaying book information—just like int and str have their own methods.

Next, let’s build a Library System and examine the code that is used to build classes.


The 3 Parts of a Class - And How To Write Them

When defining a class in Python, there are three essential parts:

The initialization (__init__)

Every class needs a way to set up its data once it's created. This is done using the initializer method __init__(), which is automatically called when a new instance is created.

Example:

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

Book Class with 3 Attributes in initializer method


The Method (Defining Behavior)

A class is more than just a data container - It also defines the possible behavior of its objects using methods. These are functions that can only operate on your class, like how the .upper() method only works on string objects.

Example:

def display_info(self):
  print(f"'{self.title}' by {self.author} ({self.year})")

Note: This code should follow immediately after the init method


The instantiation (Creating Objects)

To use the class, we have to create an instance - this process is called instantiation.

Example:

book1 = Book("1984", "George Orwell", 1949)
book2 = Book("Brave New World", "Aldous Huxley", 1932)

Note: This code can be run anywhere in the program as long as the class is already defined


Summary

  1. Initialization (__init__) → Defines the attributes (data) of an instance.
  2. Methods → Define what an instance can do.
  3. Instantiation → Creates objects from the class.

This structure allows you to model representations of real-world objects in Python, opening up all kinds of possibilities of functionality and making your code more organized.

2. The Library

The Example

In the following code we create:

  1. A Book class with attributes for title, author and year
  2. A Library class to manage selections of books
  3. Functionality for adding, removing and listing books in the library

Look out for those three while reading through the code:

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

    def display_info(self):
        return f"{self.title} by {self.author} ({self.year})"


class Library:
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)
        print(f'Book added: {book.display_info()}')

    def remove_book(self, title):
        for book in self.books:
            if book.title == title:
                self.books.remove(book)
                print(f'Book removed: {title}')
                return
        print(f'Book not found: {title}')

    def list_books(self):
        if not self.books:
            print("No books in the library.")
        else:
            print("Books available:")
            for book in self.books:
                print(f" - {book.display_info()}")


# Using our Library to add, remove and show the current books
library = Library()
library.add_book(Book("1984", "George Orwell", 1949))
library.add_book(Book("Brave New World", "Aldous Huxley", 1932))
library.list_books()
library.remove_book("1984")
library.list_books()

3. Making Your First Class and Object

The Exercise

Now that you've seen an example of how classes work, it's time to create your very own first class. When you're done, you will get to use a feedback prompt with GPT to get immediate feedback on your understanding of the content so far.

But first, open up your editor of choice (or textfile) and follow these 3 steps:

💡
Use the Library example above to look up syntax

Exercise: Creating a Car Class

Task 1: Define a Class

Create a class called Car that will store details about a car.

  • The class should have the following attributes:
    • self.brand
    • self.model
    • self.year

Task 2: Add a Method

Add a method called display_info that returns a string in the format:

"<brand> <model> - <year>"

Task 3: Create an Object

Once your class is defined, create two instances (objects) of car and display their information.


Done?

Now use this GPT prompt to check for errors.

  1. Open ChatGPT
  2. Paste your code
  3. Then paste this prompt after, press enter and get personalized feedback

GPT Prompt: Personalized Code Review

I have written Python code as part of an Object-Oriented Programming (OOP) learning exercise. "I have completed Chapters 1 & 2 of a 5-part guide available at:

If my mistake involves self or concepts from Chapter 3+, reassure me that I'll learn this soon, rather than correcting it.

Guidelines for Review

  1. Focus on What I Have Learned
    • I understand what a class is, how to define attributes with __init__, and how to instantiate objects.
    • If my code lacks proper method structure or behavior, provide general guidance without introducing self explicitly.
    • Example:
      • "Your display_info function is not quite working as intended. You’ll learn more about how functions behave inside classes in Chapter 3, but for now, make sure it returns a value instead of printing it directly."
  2. Allow Different Correct Solutions
    • If my approach is correct but different from the guide’s example, acknowledge it as valid.
    • Only suggest improvements if my approach has clear downsides.
    • Example:
      • "Your Car class correctly stores the attributes, and your object creation works as expected. You might see a different structure in the guide, but your approach is valid."
  3. Avoid Correcting Advanced Topics
    • If I forget self in methods or misuse instance variables, do not correct me yet. Instead, give me a hint and then reassure me that I will learn this soon.

Feedback Structure Example

  1. Incorrect Attribute Initialization
    • "Your class is missing an __init__ method, which is essential for setting up attributes when an object is created."
    • "Check the section 'The Initialization (__init__)' in the guide to learn how to store attributes inside a class."
  2. Incorrect Instantiation
    • "When creating an object, you need to pass the correct number of arguments to match your __init__ method."
    • "Revisit 'Instantiation (Creating Objects)' in the guide to understand how to properly create instances of a class."
  3. Function Inside a Class Not Working as Expected
    • "Your function is not behaving as expected inside your class. You’ll learn more about function behavior inside classes in Chapter 3, but for now, ensure it interacts with your attributes correctly."

Final Output Should:

  • Provide clear, structured feedback
  • Reference relevant guide sections
  • Avoid premature corrections on self, method structure, or OOP pillars
  • Encourage self-correction and learning
  • Allow for alternative valid approaches