Skip to main content
Editor

Python Classes and Objects: OOP from the Ground Up

Intermediate30 min8 exercises125 XP
0/8 exercises

Imagine you own a bakery and you have a cookie cutter shaped like a star. Every time you press it into dough, you get a new star-shaped cookie. The cutter itself isn't a cookie - it's a blueprint for making cookies.

In Python, a class is the cookie cutter, and each cookie you stamp out is an object. The class defines the shape (what data it holds) and the behavior (what it can do). Objects are the actual things you work with in your program.

In this tutorial, you'll learn how to create your own classes, give them data with __init__, add behavior with methods, and control how they display with __str__. By the end, you'll be building your own custom types in Python.

What Are Classes and Objects?

You've already used objects in Python without realizing it. A string like 'hello' is an object. A list like [1, 2, 3] is an object. Even integers are objects. Every value in Python is an object created from some class.

A class is a template that bundles together data (called attributes) and functions (called methods) into one package. An object is a specific instance of that class, with its own unique data.

Think about dogs. The concept of "Dog" is like a class - it says every dog has a name, a breed, and an age. Your specific dog "Buddy" is an object - a golden retriever who is 3 years old.

Everything in Python is an object
# You've been using classes all along!
my_list = [1, 2, 3]
print(type(my_list)) # <class 'list'>
my_name = 'Alice'
print(type(my_name)) # <class 'str'>
my_number = 42
print(type(my_number)) # <class 'int'>
Output
<class 'list'>
<class 'str'>
<class 'int'>

The type() function reveals the class behind every value. Now let's learn how to build our own classes.

How Do You Create Your First Class?

You create a class using the class keyword, followed by a name (by convention, starting with a capital letter), and a colon. The simplest class is just the keyword and pass:

The simplest class
class Dog:
pass
# Create two objects (instances) from the Dog class
dog1 = Dog()
dog2 = Dog()
print(type(dog1))
print(dog1 == dog2) # Different objects!
Output
<class '__main__.Dog'>
False

Calling Dog() creates a brand-new Dog object. Each call makes a separate, independent object - just like each press of the cookie cutter makes a separate cookie.

What Is the __init__ Method?

A Dog class without any data isn't very useful. We need a way to give each dog its own name, breed, and age when we create it. That's exactly what __init__ does.

__init__ is a special method (called a constructor) that runs automatically every time you create a new object. It sets up the object's initial data.

Using __init__ to set up data
class Dog:
def __init__(self, name, breed, age):
self.name = name
self.breed = breed
self.age = age
# Create a dog with specific data
buddy = Dog('Buddy', 'Golden Retriever', 3)
print(buddy.name)
print(buddy.breed)
print(buddy.age)
Output
Buddy
Golden Retriever
3

Let's break this down piece by piece:

  • def __init__(self, name, breed, age) - defines the constructor. The double underscores mean it's a special Python method.
  • self - refers to the specific object being created. It's how the object talks about itself.
  • self.name = name - stores the name argument as an attribute on the object. Now buddy.name will return 'Buddy'.
  • Each object has its own data
    class Dog:
    def __init__(self, name, breed, age):
    self.name = name
    self.breed = breed
    self.age = age
    # Each object has its own separate data
    buddy = Dog('Buddy', 'Golden Retriever', 3)
    max_dog = Dog('Max', 'German Shepherd', 5)
    print(f'{buddy.name} is {buddy.age} years old')
    print(f'{max_dog.name} is {max_dog.age} years old')
    Output
    Buddy is 3 years old
    Max is 5 years old

    How Do Instance Methods Work?

    Attributes store data. Methods define behavior - they're functions that live inside a class and can access the object's data through self.

    Adding methods to a class
    class Dog:
    def __init__(self, name, breed, age):
    self.name = name
    self.breed = breed
    self.age = age
    def bark(self):
    return f'{self.name} says: Woof!'
    def birthday(self):
    self.age += 1
    return f'Happy birthday {self.name}! Now {self.age} years old.'
    buddy = Dog('Buddy', 'Golden Retriever', 3)
    print(buddy.bark())
    print(buddy.birthday())
    print(buddy.birthday())
    Output
    Buddy says: Woof!
    Happy birthday Buddy! Now 4 years old.
    Happy birthday Buddy! Now 5 years old.

    Notice two things. First, bark() reads self.name to personalize the message. Second, birthday() actually changes self.age - methods can modify the object's data, not just read it.

    You call methods using dot notation: buddy.bark(). Python automatically passes buddy as self, so the method knows which dog is barking.

    Without classes (scattered data)
    dog1_name = 'Buddy'
    dog1_age = 3
    
    def bark(name):
        return f'{name} says: Woof!'
    
    print(bark(dog1_name))
    With classes (organized)
    class Dog:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def bark(self):
            return f'{self.name} says: Woof!'
    
    buddy = Dog('Buddy', 3)
    print(buddy.bark())

    Classes bundle related data and behavior together. When your program has 50 dogs, the class approach scales cleanly while the scattered-variable approach becomes chaos.

    What Is the Difference Between Class and Instance Attributes?

    So far, every attribute we created was an instance attribute - data unique to each object. But sometimes you want data that's shared across all objects of a class. That's a class attribute.

    Class attribute vs instance attribute
    class Dog:
    species = 'Canis familiaris' # Class attribute (shared)
    def __init__(self, name, breed):
    self.name = name # Instance attribute (unique)
    self.breed = breed # Instance attribute (unique)
    buddy = Dog('Buddy', 'Golden Retriever')
    max_dog = Dog('Max', 'German Shepherd')
    # Both share the same species
    print(buddy.species)
    print(max_dog.species)
    # But have different names
    print(buddy.name)
    print(max_dog.name)
    Output
    Canis familiaris
    Canis familiaris
    Buddy
    Max

    Class attributes are defined directly inside the class body, outside any method. Instance attributes are defined inside __init__ using self..

    Using a class attribute as a counter
    class Dog:
    total_dogs = 0 # Class attribute: tracks count
    def __init__(self, name):
    self.name = name
    Dog.total_dogs += 1 # Modify via the class name
    print(f'Dogs created: {Dog.total_dogs}')
    dog1 = Dog('Buddy')
    dog2 = Dog('Max')
    dog3 = Dog('Luna')
    print(f'Dogs created: {Dog.total_dogs}')
    Output
    Dogs created: 0
    Dogs created: 3

    How Do __str__ and __repr__ Control Display?

    If you try to print an object without defining __str__, you get an ugly, unhelpful message like <__main__.Dog object at 0x7f...>. Let's fix that.

    Without __str__ (ugly output)
    class Dog:
    def __init__(self, name, breed, age):
    self.name = name
    self.breed = breed
    self.age = age
    buddy = Dog('Buddy', 'Golden Retriever', 3)
    print(buddy) # Not helpful!
    Output
    <__main__.Dog object at 0x4affc90>

    The __str__ method lets you define a human-friendly string for your object. Python calls it whenever you use print() or str() on the object.

    With __str__ and __repr__
    class Dog:
    def __init__(self, name, breed, age):
    self.name = name
    self.breed = breed
    self.age = age
    def __str__(self):
    return f'{self.name} ({self.breed}), age {self.age}'
    def __repr__(self):
    return f'Dog(\'{self.name}\', \'{self.breed}\', {self.age})'
    buddy = Dog('Buddy', 'Golden Retriever', 3)
    print(str(buddy)) # Human-friendly
    print(repr(buddy)) # Developer-friendly
    Output
    Buddy (Golden Retriever), age 3
    Dog('Buddy', 'Golden Retriever', 3)

    The difference is audience. __str__ is for end users - it should be readable and friendly. __repr__ is for developers - it should look like valid Python code that could recreate the object.

    How Does a Complete Class Look?

    Let's build a BankAccount class that combines everything you've learned: __init__, instance methods, class attributes, and __str__.

    Complete BankAccount class
    class BankAccount:
    bank_name = 'PyBank' # Class attribute
    def __init__(self, owner, balance=0):
    self.owner = owner
    self.balance = balance
    def deposit(self, amount):
    self.balance += amount
    return f'Deposited ${amount}. New balance: ${self.balance}'
    def withdraw(self, amount):
    if amount > self.balance:
    return 'Insufficient funds!'
    self.balance -= amount
    return f'Withdrew ${amount}. New balance: ${self.balance}'
    def __str__(self):
    return f'{self.owner}\'s {BankAccount.bank_name} account: ${self.balance}'
    account = BankAccount('Alice', 100)
    print(account)
    print(account.deposit(50))
    print(account.withdraw(30))
    print(account.withdraw(200))
    print(account)
    Output
    Alice's PyBank account: $100
    Deposited $50. New balance: $150
    Withdrew $30. New balance: $120
    Insufficient funds!
    Alice's PyBank account: $120

    This is the power of classes. The BankAccount class packages all the data (owner, balance) and all the rules (can't withdraw more than you have) into one clean, reusable unit.


    Practice Exercises

    Create a Book Class
    Write Code

    Create a Book class with an __init__ method that takes title, author, and pages as parameters and stores them as instance attributes. Then create a book with title '1984', author 'George Orwell', and pages 328. Print each attribute on its own line.

    # Create your Book class here
    Add a Method to Rectangle
    Write Code

    Create a Rectangle class with width and height attributes. Add an area() method that returns the area (width times height). Create a rectangle with width 5 and height 3, then print the result of calling area().

    # Create your Rectangle class here
    Predict the Counter Output
    Predict Output

    Read the code carefully and predict what it prints. Think about what __init__ sets and how increment() changes self.count.

    class Counter:
        def __init__(self):
            self.count = 0
    
        def increment(self):
            self.count += 1
            return self.count
    
    c = Counter()
    print(c.increment())
    print(c.increment())
    print(c.increment())
    # Type the exact output you predict:
    class Counter:
    def __init__(self):
    self.count = 0
    def increment(self):
    self.count += 1
    return self.count
    c = Counter()
    print(c.increment())
    print(c.increment())
    print(c.increment())
    Fix the Student Class
    Fix the Bug

    This Student class has two bugs. Fix them so the code prints:

    Alice: 85.0
    class Student:
    def __init__(self, name):
    self.name = name
    grades = []
    def add_grade(self, grade):
    self.grades.append(grade)
    def average(self):
    return sum(self.grades) / len(self.grades)
    s = Student('Alice')
    s.add_grade(90)
    s.add_grade(80)
    print(f'{s.name}: {s.average()}')
    Add __str__ to a Product
    Write Code

    Create a Product class with name and price attributes. Add a __str__ method that returns the format 'Product: <name> - $<price>'. Create a product with name 'Laptop' and price 999.99, then print it.

    # Create your Product class here
    Build a Player Class with Score Tracking
    Write Code

    Create a Player class with:

  • A class attribute total_players starting at 0
  • __init__ takes name and sets self.score = 0, and increments Player.total_players
  • A win_round(self, points) method that adds points to self.score
  • Create two players 'Alice' and 'Bob'. Alice wins a round with 10 points, then Bob wins with 15 points. Print each player's score and the total number of players in this exact format:

    Alice: 10
    Bob: 15
    Total players: 2
    # Create your Player class here
    Refactor Functions into a Class
    Refactor

    Refactor this code into a ShoppingCart class. The class should have:

  • __init__ that creates an empty items list
  • add_item(self, name, price) that appends a tuple (name, price) to items
  • total(self) that returns the sum of all prices
  • __str__ that returns 'Cart: <N> items, total $<total>'
  • Then create a cart, add 'Apple' for 1.50 and 'Bread' for 3.00, and print the cart.

    # Original code to refactor:
    cart_items = []
    
    def add_item(cart, name, price):
        cart.append((name, price))
    
    def get_total(cart):
        return sum(price for _, price in cart)
    
    add_item(cart_items, 'Apple', 1.50)
    add_item(cart_items, 'Bread', 3.00)
    print(f'Cart: {len(cart_items)} items, total ${get_total(cart_items)}')
    # Refactor into a ShoppingCart class
    A Recent Items List
    Stretch

    Editors keep a list of the files you opened last. Write a class RecentItems that does the same:

  • RecentItems(limit) makes an empty list that holds at most limit items.
  • add(item) puts the item at the front. If it is already in the list, it moves to the front instead of appearing twice. If the list is now longer than limit, the oldest item is dropped.
  • items() returns the items as a new list, newest first. Changing that list must not change the object.
  • recent = RecentItems(3)
    recent.add("a.py")
    recent.add("b.py")
    recent.add("a.py")
    recent.items()   # ['a.py', 'b.py']

    Some of the tests are hidden.

    class RecentItems:
    pass
    Solution unlocks after your first Check

    Harder problems

    More problems on this topic: Classes

    Related Tutorials

    Was this tutorial helpful?