Classes and Objects
A class describes how objects of one kind are built. The __init__ method sets up each new object, and self refers to the particular instance being created or used.
Create a simple class and give each instance its own data.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Classes and Objects
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
If you are tracking several books, a title and page count belong together. A class describes the kind of thing you want to create, and an object is one particular instance of that class. Each book can have its own title and page count while sharing the same way to produce a summary. In this lesson we will build a Book class, make two books, and trace how Python knows which data a method should use. Then we will see an object change its own state, protect a wallet's balance with a method, and give each reading list a separate collection. You do not need classes for every small script. They become useful when data and the actions tied to that data form a meaningful unit.
- 00:42
Before pressing Run, ask which object a method belongs to and which values are stored on that object. That simple question prevents many of the most confusing beginner mistakes. Start with class Book. Inside it, the special method whose name has double underscores around init runs when we create a new Book. The constructor call supplies Python Notes and eighty. Python also supplies the new instance as the first argument, traditionally named self. The two assignments save the provided values on that particular object as self.title and self.pages. After the call, first_book refers to an object carrying those values.
- 01:23
When we call first_book.summary, Python passes first_book as self. The method builds a string from that instance's title and pages, returns it, and print displays Python Notes: eighty pages. Create second_book with Code Journal and one hundred twenty. The class instructions are shared, but the stored values are different. Calling second_book.summary uses the second object's data. Calling first_book.summary again still uses the first object's data. One object was not overwritten by creating another. The lesson's Counter example makes independence even clearer: changing first.value to two leaves second.value at zero.
- 02:04
Both are instances of Counter, but each was initialized separately. Methods can also change an object's state. In the Lamp guide example, a new lamp begins with is_on set to False. status returns Off. Calling switch_on changes that lamp's is_on attribute to True, so the next status call returns On. We use a method when an action belongs naturally to the object. A Wallet gives us a more important reason. Its spend method rejects amounts that are zero or negative, and amounts greater than the balance. A rejected spend returns False and leaves the balance untouched. Spending seven from ten succeeds, returns True, and leaves three.
- 02:47
The next attempt to spend five fails because five is now greater than three. Keeping this check in spend means callers can use the same rule every time rather than remembering to check the balance at each call site. A ReadingList shows another form of independent state. Its constructor creates a new empty titles list for every instance. Add Dune to the first list, and the second remains empty. If each object is supposed to have its own collection, create that collection on self during initialization. Pause and predict what happens if you add a second title to the first ReadingList. Only the first object's titles should change.
- 03:28
Classes are easiest to understand by drawing two boxes for two objects and writing their attributes inside each box. A method call is then an action on one box, not on the class as a whole. The first common error is defining summary without self. When you call a method through an instance, Python passes that instance automatically. If the method signature has no first parameter to receive it, Python raises TypeError. Add self to the method definition and try again. The second error is writing title equals title inside the constructor. That only reassigns the local parameter to itself.
- 04:08
It does not create an attribute on the object. Later, book.title raises AttributeError because no title was saved. Write self.title equals title to attach the value to the instance. These two lines look similar, but the left side tells you where the value is stored. A further design mistake is putting a mutable list in a place shared by every object when you expect separate lists. That can make adding to one reading list appear in another. Construct a fresh empty list on self for each instance. When debugging a class, inspect how each attribute is initialized and which instance receives each method call. You can make a tiny diagnostic by printing the title of each book in turn.
- 04:52
If both titles unexpectedly match, trace the assignments and check whether you are changing a shared value instead of an instance attribute. This is especially useful once a class grows beyond two or three fields, because the original constructor line may be far from the surprising output. Do not assume two objects share state just because they share a class, or that a local name becomes an attribute without self. The practical task is to make a second Book called Code Journal with one hundred twenty pages. Store it in second_book, print its summary, and then print the first book's summary again. Predict both lines before you run.
- 05:33
The second should say Code Journal: one hundred twenty pages; the first should still say Python Notes: eighty pages. Check the task after your code runs. For extra practice, create a third book and change only its pages. Then print all three summaries to test instance independence. The quiz checks what self refers to, when the initializer runs, and how separate objects hold their own attributes. If you can answer those questions by drawing two boxes of state, you have the core mental model. The next lesson uses dictionaries for labeled data when a full class would be more structure than you need.
Understand the concept
An instance can store data in attributes such as self.title. Methods are functions attached to the class. Calling an instance method passes that instance as self automatically.
- class defines a type
- __init__ sets instance attributes
- self refers to the instance
See it step by step
Read the code, predict the output, then compare it with the result.
01. Build and describe an object
class Dog:
def __init__(self, name):
self.name = name
def describe(self):
return f"Dog: {self.name}"
pet = Dog("Pip")
print(pet.describe())Dog: Pip__init__ stores the argument on this object. The method reads that stored attribute through self.
02. Keep objects independent
class Counter:
def __init__(self):
self.value = 0
first = Counter()
second = Counter()
first.value = 2
print(first.value)
print(second.value)2
0Each new Counter has its own value. Changing first does not change second.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
A method can change an object's state
An object is useful when data and the actions on that data belong together. A lamp has an on/off state, and its methods describe the allowed actions. Rather than changing a variable somewhere else in the program, we ask the lamp to switch on. The instance keeps its state between method calls, so the next method sees the new value.
The __init__ method runs for every new Lamp and starts each one in the same sensible state. The state is stored as self.is_on, not as a temporary local variable. A method may return a description without changing anything. Predict the final output if you remove the switch_on() call, then try adding a second lamp and switching on only one of them.
class Lamp:
def __init__(self):
self.is_on = False
def switch_on(self):
self.is_on = True
def status(self):
return "On" if self.is_on else "Off"
desk_lamp = Lamp()
print(desk_lamp.status())
desk_lamp.switch_on()
print(desk_lamp.status())Off
On- Lamp() creates an instance whose is_on attribute starts False.
- switch_on() updates that instance's attribute.
- status() reads the current attribute each time it is called.
Keep an important rule next to the data
A class can give callers one convenient place for a rule. This wallet's spend() method checks whether a purchase is affordable before changing balance. Callers that use spend() get the same check instead of repeating it throughout a program. This example does not prevent direct assignment to wallet.balance or reject a negative starting balance, so it is not a full balance guarantee.
This simple example uses whole-number units so that decimal rounding does not distract from the rule. The method returns False for a nonpositive or unaffordable amount and leaves the balance unchanged. It returns True only after subtraction. Predict the balance after a failed spend(5), then try spend(3) and inspect both the return value and final balance.
class Wallet:
def __init__(self, balance):
self.balance = balance
def spend(self, amount):
if amount <= 0 or amount > self.balance:
return False
self.balance -= amount
return True
wallet = Wallet(10)
print(wallet.spend(7))
print(wallet.spend(5))
print(wallet.balance)True
False
3- The first spend passes the guard and changes 10 to 3.
- The second spend fails; the early return leaves 3 untouched.
- The caller can use the Boolean result instead of guessing what happened.
Give each instance its own mutable collection
Lists can change after an object is created, which makes their placement important. If a reading list belongs to one learner, create it inside __init__ as self.titles = []. Then each new ReadingList receives a separate empty list. Putting a mutable list directly on the class would share one list among instances unless you carefully override it.
This is a practical reason to distinguish class-level facts from instance-level state. A fixed category might belong on the class, while a learner's book titles belong on that learner's instance. After running the example, add a title to second and predict whether first changes. Try creating a third list and confirm it starts empty.
class ReadingList:
def __init__(self):
self.titles = []
def add(self, title):
self.titles.append(title)
first = ReadingList()
second = ReadingList()
first.add("Dune")
print(", ".join(first.titles))
print(len(second.titles))Dune
0- Each __init__ call creates a new list object.
- add() changes only the list reached through that instance's self.
- second still has zero titles.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Construct second_book = Book('Code Journal', 120). Call second_book.summary() inside print(), then call first_book.summary() again.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Omitting self in a method
class Book:
def summary():
return "A book"
book = Book()
print(book.summary())class Book:
def summary(self):
return "A book"
book = Book()
print(book.summary())What happens: TypeError because Python passes the instance automatically.
Instance methods need self as their first parameter.
Forgetting self on an attribute
class Book:
def __init__(self, title):
title = title
book = Book("Python Notes")
print(book.title)class Book:
def __init__(self, title):
self.title = title
book = Book("Python Notes")
print(book.title)What happens: AttributeError because no title attribute was stored on the object.
Assign to self.title to save the value on the instance.