Skip to content
AI-grafen
DAI developerProgramming· about 45 min· fundamentals that rarely change· verified 2026-09-20· EN

Python — classes and objects

Be able to define classes with attributes and methods and understand why nn.Module is a class.

Prerequisites

Intuition

Think of a class as a template, or a blueprint for building houses. The blueprint itself (the class) contains information about how many rooms there should be and what the kitchen should look like, but it is not an actual house you can live in. When you build a house from the blueprint you create an object, or an instance. Every house you build is unique; one can be painted red and another blue. Those properties are called attributes.

In Python classes are also dynamic, which means they are created while the program runs and can be changed afterwards [1]. A class bundles together data (attributes) and functions (methods) that operate on that data [1]. A class for a car, for instance, can have attributes for colour and speed, plus a method for starting the engine. Using classes lets us create many different cars (objects) that all follow the same basic structure but have different values for their attributes. This makes the code more organised and more reusable [1].

Code

Here is an example of how to define a simple class in Python. We create a class Car with a method __init__ that runs automatically when we create a new object. self refers to the specific object being created [4].

class Car:
    def __init__(self, colour):
        self.colour = colour  # An attribute
        self.speed = 0

    def start(self):
        self.speed = 10
        return f"The car is {self.colour} and is doing {self.speed} km/h"

# Create an instance
my_car = Car("blue")
print(my_car.start())

In deep learning nn.Module is a special class in PyTorch. It is the base class for all neural networks [2]. When you define a model that inherits from nn.Module you usually have to define a forward method. That method describes how the data flows through the network. PyTorch automatically handles computing the derivatives and storing the parameters, thanks to nn.Module being a class designed for exactly that [2]. Understanding that nn.Module is a class helps you see how models are built as objects with state and behaviour [2].

Mastery means

  • Be able to define a Python class with attributes and methods, including how self is used.
  • Understand the difference between a class object and an instance object, and how __init__ initialises an object.
  • Understand that nn.Module is a base class in PyTorch that handles the parameters and the forward method.

Sign in to do the exercises and build your mastery up.

Sources

All the sources and licences