Lesson 5 of 148 min
Classes, just enough
A class is a plan for objects: each object keeps its own values, and its methods reach them through self.
After this lesson you can read a class such as a PyTorch module or a scikit-learn model.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Two taxis, two rates
One class can make as many objects as you like, and each keeps its own values. In other code you will read two more words for these: a value kept on an object, such as rate, is an attribute, and an object made from a class is an instance of it.
class Taxi:
def __init__(self, rate):
self.rate = rate
def price(self, km):
return self.rate * km
city = Taxi(2)
airport = Taxi(3)
print(city.price(10), airport.price(10))
print(city.rate, airport.rate)20 30 2 3
A method with no self
The slip that turns the lesson around: self left out of the method. Python still puts the object before the dot in, so the method gets one input more than it asks for.
class Taxi:
def __init__(self, rate):
self.rate = rate
def price(km):
return 2 * km
my_taxi = Taxi(2)
print(my_taxi.price(10))TypeError: Taxi.price() takes 1 positional argument but 2 were given
A PyTorch model with no super
Leave super().__init__() out of a PyTorch model, and it stops on the line that keeps the first part on self. Module's own init never ran, so the object is not ready to keep PyTorch parts.
from torch import nn
class Taxi(nn.Module):
def __init__(self):
self.cost = nn.Linear(1, 1)
my_taxi = Taxi()AttributeError: cannot assign module before Module.__init__() call
A scikit-learn model keeps what it learned
scikit-learn's models are objects too. Give one three taxi rides, and fit keeps the rate and the start fee it learned on the object. The names end in _, scikit-learn's mark for a value learned from data.
from sklearn.linear_model import LinearRegression
km = [[1], [5], [10]]
paid = [5, 13, 23]
model = LinearRegression()
model.fit(km, paid)
print(model.coef_, round(model.intercept_, 2))[2.] 3.0
The older way to write super
In older PyTorch code, the first line of init names the class and self inside the brackets. It does the same thing. And whichever way init starts, you call the object, as in the lesson, never forward by hand: calling the object lets PyTorch do its own work around forward.
from torch import nn
class Taxi(nn.Module):
def __init__(self):
super(Taxi, self).__init__()
self.cost = nn.Linear(1, 1)
my_taxi = Taxi()
print(my_taxi.cost)Linear(in_features=1, out_features=1, bias=True)
Run on Python 3.13.3, PyTorch 2.15.0 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
price is written as def price(self, km). You make my_taxi = Taxi(3), then call my_taxi.price(4) with one number. Inside price, what is self?
2 of 2
Two taxis from one class. What does this print?
class Taxi:
def __init__(self, rate):
self.rate = rate
def price(self, km):
return self.rate * km
cheap = Taxi(2)
fast = Taxi(3)
print(cheap.price(4))The ideas in this lesson
- Class and object
- A class is a plan. Calling it with brackets makes a new object, which keeps its own values.
- self
- A method is a function inside a class. Called after a dot, it gets the object before the dot as self.
- Inheritance
- A class can inherit from another class and then has everything that class can do, as PyTorch models do.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Hook
Here's a puzzle. Every model in this series is made from a class. And this function comes from a class. It's called price, and it asks for two inputs. But the line under it gives price just one number. A function needs every input it asks for. When one is missing, Python stops. So will this line print a price? Or will it stop?
A class is a plan
Keep your guess. In this chapter, you'll make an object from a class. You'll see what self is: a small word that's in every class. And you'll read a real PyTorch model.
First, here's a small class about a taxi. Its name is Taxi. So what does it make when Python runs it?
Watch. Python reads the class line, and the first line of each of its two functions. The lines inside the functions wait. And nothing is made.
That's because a class is a plan. This plan says two things.
Each taxi keeps a rate: the price of one kilometre.
And each taxi can work out the price of a ride.
A plan is not a taxi. Not yet.
Calling the class
Line seven uses the class. It calls Taxi with brackets, the way you call a function. And it passes a two: the rate.
So which line runs next?
Not line eight. Python jumps back up... to line three.
This part of the class is called init. The two arrives here, as rate. Init asks for self as well. We'll get to self in a moment.
Python runs init by itself, every time the class is called.
The object
So what does line seven make? Watch it finish.
Line seven hands back something new: an object, made from the class. Now it gets its name, my taxi.
The class is the plan. My taxi is one object made from it.
The object keeps its values
So where is the two now? Look at line three again.
Python made this object at the start of line seven, before init ran. Then it gave the object to init, as self. That's how init got two inputs from one number.
So line three says: the rate of this object is two.
And the object keeps it. Init is finished, and the two is still there, on my taxi.
An object is one thing made from a class... and it keeps its own values.
One number for two inputs
My taxi is an object, and it keeps a rate of two. Now line eight asks my taxi for a price.
Price is a method. A method is a function written inside a class. You call it after a dot, the way you call split on a piece of text.
Price asks for two inputs: self, and km, the kilometres. Line eight gives it one number. Ten.
So, a price... or an error?
The object before the dot
Let's run it... Twenty. A price.
If you said an error, that's the right rule for a function. But a method gets one more input, from the dot.
My taxi is before the dot. When you call a method after a dot, Python takes the object before the dot. It puts it in as self. So my taxi goes in as self, and the ten goes to km.
The object before the dot... goes in as self.
So the rate on self is my taxi's own rate. Two, times ten. Twenty.
Another rate
Now make the taxi with a rate of three. Line eight stays the same. And now it says thirty.
The price comes from the object before the dot.
The mistake everyone makes
Here's a mistake everyone makes once. Line seven loses its brackets.
What will line eight do now?
No object, nothing to be self
It stops.
And look at what Python says. Km is missing. But we gave it ten!
Here's why. Without brackets, nothing is made. My taxi is the class itself. Not an object.
Only an object before the dot goes in as self. Here, a class stands before the dot. So nothing goes in. The ten takes the place of self... and km gets nothing.
If you guessed that the rate would be missing, good thinking. But Python stops before it gets that far.
The fix: put the brackets back. Taxi, two.
No object before the dot... nothing to be self.
A real model
Now a real model. This one is written with PyTorch, the library this series uses to build its models. It's a taxi again. And you can already read most of it.
Most lines have a twin
Here's a taxi model written for PyTorch, beside a plain Python one. Most of its lines have a twin.
So when you make this object, which lines run?
Init does, because making an object runs init. Its last line keeps something on self, called cost.
Cost is an object made from another PyTorch class, called Linear. It keeps two numbers. For a taxi, a rate and a start fee.
Two things have no twin.
Those are the new parts.
Inheriting
The first new part is in the brackets after the class name. What is that doing there? Inside them is Module, PyTorch's class for models. Taxi is built on Module. So Taxi gets everything that Module can do, without writing any of it again.
This is called inheriting. Taxi inherits from Module.
Module's init first
The second new part is the first line of init. It starts with super. Super means the class that Taxi inherits from. So this line runs Module's own init.
Module's init gets the object ready to keep PyTorch parts. That's why it runs first, before cost is kept on self.
Calling the object
Now look at the method, forward. Nothing in this code ever calls it. The last line calls the object itself, with km in brackets.
So what runs?
Forward does. When you call a PyTorch object, it runs forward for you, with my taxi as self, and the kilometres as km.
Forward is Taxi's own method. But Taxi inherits this from Module: when you call the object, forward runs.
So a PyTorch model is a class. Init keeps its parts on self, and forward uses them.
Its own values
So here's what you saw. A class is a plan, and an object is one thing made from it. Each object keeps its own values. And its methods reach them through self.
The lab
That's the end of this unit. In its lab, you use these two lessons to turn a sentence into numbers, all inside a class.
Close
So in a method call, self is the object before the dot. Now try it on this lesson's page, and take the quiz. Take self away from the rate on line five. Then find out what Python says, and why.
You use this lesson in Lab 2: A tiny tokenizer, which comes next.
Facts last checked on .
