Python + AI/ML · Tutorial 6 of 6
Python OOP: classes and objects, explained simply
By the FUTEAC Team · 19 November 2026 · 13 min read · Beginner
In short
A class is a blueprint for making objects, and an object is one thing made from that blueprint, with its own data. In Python you write the blueprint once with class, build objects with __init__, and give them behaviour with methods. This tutorial builds a library system: a Book class, a checkout method, and an EBook that inherits from Book.
- A class is the blueprint, an object is the thing built from it. You write
class Bookonce, then make as many books as you like, each with its own title and copy count. __init__sets up each object. It runs when you create an object, and it stores the starting data on that object withself.- A method is a function that belongs to the object. It reads and changes that object's data, and it always takes
selfas its first parameter. - Inheritance reuses the parent class. A child class gets the parent's methods for free and adds or changes only what is different.
- Use a class when data has behaviour. A dictionary holds data. A class holds data plus the actions that belong with it, like checking a book out.
- This tutorial feeds the Python Programming Foundations course (/course/python-programming-foundations) and the Object-Oriented Python (/skill/python-oop) skill.
Before you start
What is a class, and what is an object?
A class is a recipe card. An object is the dish you cook from it. One card can make many dishes, and each dish is separate: salting one does not salt the others. In the same way, one Book class can make many book objects, and checking out one book does not change the copy count of another.
Here is the same idea with plain data first. A book as a dictionary looks like this:
book = {"title": "Dune", "author": "Frank Herbert", "copies": 3}That works until you need behaviour. Checking a book out means changing copies, but only if a copy is left, and refusing politely when none is left. With dictionaries, that logic lives in a separate function, and every place in your program that checks a book out must remember the rule. With a class, the rule lives with the data, in one place.
A class bundles data and behaviour together. The data is the attributes: title, author, copies. The behaviour is the methods: checkout, describe. Every object made from the class carries the same methods and its own copy of the data.
You already use objects every day in Python, even if you have never written a class. A list is an object, and append is its method. A string is an object, and upper is its method. Writing your own class is doing for your own data what Python already does for lists and strings.
---
Your first class: `__init__` and attributes
Write the class in a file called library.py:
class Book:
def __init__(self, title, author, copies):
self.title = title
self.author = author
self.copies = copiesThree things to notice. First, the class name starts with a capital letter by convention: Book, not book. Second, __init__ is a special method with two underscores on each side, called the initialiser. Python runs it automatically when you create an object. Third, self is the object being created. Writing self.title = title means "store this title on this particular object".
Create two books from the class:
book1 = Book("Dune", "Frank Herbert", 3)
book2 = Book("Pride and Prejudice", "Jane Austen", 1)Book("Dune", "Frank Herbert", 3) calls __init__ with self set to the new object, so the three values land on that object and nowhere else. Read an attribute back with a dot:
print(book1.title)
print(book2.copies)Dune
1Each object remembers its own values. book1 has 3 copies, book2 has 1, and neither knows about the other.
---
Methods: behaviour that belongs to the object
Add two methods to the class. checkout takes one copy if any is left and reports whether it worked. describe returns a one-line summary:
class Book:
def __init__(self, title, author, copies):
self.title = title
self.author = author
self.copies = copies
def checkout(self):
if self.copies > 0:
self.copies -= 1
return True
return False
def describe(self):
return f"{self.title} by {self.author}: {self.copies} left"A method is a function defined inside the class, and its first parameter is always self. When you call book1.checkout(), Python passes book1 in as self for you, so self.copies inside the method means book1's copies. That is the whole trick: the method knows which object it belongs to, so you never pass the object in by hand.
Run the class end to end:
book1 = Book("Dune", "Frank Herbert", 3)
book2 = Book("Pride and Prejudice", "Jane Austen", 1)
print(book1.describe())
print(book2.describe())
print(book1.checkout())
print(book1.describe())
print(book2.checkout())
print(book2.checkout())
print(book2.describe())Output:
Dune by Frank Herbert: 3 left
Pride and Prejudice by Jane Austen: 1 left
True
Dune by Frank Herbert: 2 left
True
False
Pride and Prejudice by Jane Austen: 0 leftRead the story the output tells. book1 starts with 3 copies, one checkout takes it to 2. book2 starts with 1 copy: the first checkout works and returns True, the second finds nothing left and returns False, and the count stays at 0 instead of going negative. The rule "never go below zero" lives in one place, inside checkout, and every caller gets it for free.
---
One class, many objects: each keeps its own state
The last example already proves the point, but it is worth saying plainly because it is the most common confusion for beginners: objects made from the same class do not share data. book1.checkout() changed book1.copies from 3 to 2 and left book2.copies at 1.
The analogy from the start holds: one recipe card, many dishes. The card says what a dish is and how to make it. Salting your plate does not salt mine. If two objects ever seem to change together, the cause is almost always that both names point at the same object, not two objects from one class. That happens when you write book3 = book1 instead of book3 = Book(...). The first line copies the reference, so book3 is book1 under another name. The second line builds a new, separate object.
---
Inheritance: an `EBook` is a `Book` with one extra thing
An ebook is a book, plus a file size. It has a title, an author and copies, and it can be checked out, exactly like a paper book. The only difference is the download size. Inheritance lets you say that in code instead of copying the whole class:
class EBook(Book):
def __init__(self, title, author, copies, file_size_mb):
super().__init__(title, author, copies)
self.file_size_mb = file_size_mb
def describe(self):
return f"{super().describe()} ({self.file_size_mb} MB download)"class EBook(Book) says the new class inherits from Book. super().__init__(title, author, copies) runs the parent's initialiser, so the title, author and copies are set up exactly as before. The child class only adds what is new: file_size_mb. The describe method calls the parent's version with super().describe() and adds the download size to the end, instead of rewriting the whole sentence.
Add an ebook to the demo and run it:
ebook = EBook("Dune", "Frank Herbert", 5, 4)
print(ebook.describe())
print(isinstance(ebook, Book))Dune by Frank Herbert: 5 left (4 MB download)
Trueisinstance(ebook, Book) returns True, because an EBook is a Book. That is the test for whether inheritance fits: if you can say "an X is a Y" and mean it, X can inherit from Y. An ebook is a book. A checkout method that works on a Book works on an EBook without changing a line, because the child class inherited it.
Think of a child class like a standard form with one extra box added at the bottom. The form is the same form, the extra box is the only difference, and anything that knows how to read the standard form can still read the new one.
---
The wrong turn: forgetting `self`
Every Python learner meets this error, usually on the first class they write. Define a method without self:
class Book:
def describe():
return "a book"
b = Book()
print(b.describe())Python answers:
Traceback (most recent call last):
File "wrong.py", line 6, in <module>
print(b.describe())
^^^^^^^^^^^^
TypeError: Book.describe() takes 0 positional arguments but 1 was givenThe message sounds backwards at first. You wrote a method that takes nothing, and Python complains it was given one argument. The one argument is the object itself: when you write b.describe(), Python calls describe(b), passing the object in as the first argument. Your method has no parameter to receive it, so the call fails.
The fix is one word. Add self as the first parameter:
class Book:
def describe(self):
return "a book"Now b.describe() passes b into self, and the method works. The rule is simple and has no exceptions for ordinary methods: the first parameter of a method is always self, and you never pass it yourself. Python does that part for you.
---
When a class helps and when a dictionary is enough
Not every group of values needs a class. Our opinion: use a dictionary when the data is just data, and use a class when the data has rules or actions attached to it.
A dictionary is right for a settings file, a row of data you are passing along, or a quick count of things. A class is right when you catch yourself writing the same check in three places, like "only check out if copies are left", or when two or three functions always take the same dictionary as their first argument. That repeated argument is a sign the functions belong to the data, and a class is how you say that.
A class also pays off when the data has more than one shape. A library with paper books and ebooks is one class plus a small child class, not two dictionaries with different keys and an if in every function to tell them apart.
---
Try it yourself
Extend the library in library.py: 1. Add a return_book method to Book that adds one copy back and returns the new count. Test it: check a book out twice, return it once, and print the count after each step. 2. Add a Member class with a name and a borrowed list that starts empty. Give it a borrow method that takes a Book, calls checkout on it, and only adds the book to borrowed when checkout returns True. 3. Create a member called Ayesha, let her borrow book1 and book2, and print how many books she holds and how many copies each book has left. Then let her borrow book2 again and watch the method refuse, because no copy is left. If step 3 works, you have built two classes that talk to each other, which is what real object-oriented programs look like: small objects, each minding its own data, calling each other's methods.
Continue in the free course: Python Programming Foundations →
Common mistakes
- Forgetting
selfin a method. The error isTypeError: Book.describe() takes 0 positional arguments but 1 was given. Addselfas the first parameter of every method. - Calling a method on the class instead of the object.
Book.describe()fails withTypeError: Book.describe() missing 1 required positional argument: 'self', because there is no object to pass in. Call it on an object, likebook1.describe(). - Reading an attribute that
__init__never set. If you writeself.title = titlebut forgetself.copies = copies, thenb.copiesfails withAttributeError: 'Book' object has no attribute 'copies'. Set every attribute in__init__, so every object starts complete. - Assigning one object to another name and expecting a copy.
book3 = book1makes two names for the same object, so changing one changes the other. Build a new object withBook(...)when you want a separate one. - Putting behaviour in a function when it belongs in a method. If a function always takes the same dictionary as its first argument, or the same check appears in three places, that logic belongs inside the class as a method.
Frequently asked questions
What is the difference between a class and an object?
A class is the blueprint. An object is one thing built from it. class Book defines what every book has and can do. book1 = Book("Dune", "Frank Herbert", 3) builds one specific book with its own data. You can build a hundred books from one class, and each keeps its own copy count.
Do I need classes to write Python?
No, and you should not reach for them first. Functions, lists and dictionaries carry you a long way, through the whole Python Programming Foundations course. Classes earn their place when your data has rules and behaviour that keep getting repeated, or when you start using libraries like pandas, where the objects are handed to you and you call their methods.
What does __init__ actually do?
It runs once, at the moment you create an object, and sets the object up. Book("Dune", "Frank Herbert", 3) creates an empty object, runs __init__ with those three values, and hands you the finished object. If __init__ does not set an attribute, the object does not have it, and reading it later raises an AttributeError.
Why is self needed? Can't Python work it out?
Python passes the object into the method for you, but the method still needs a name to refer to it by, and that name is self. Without it, the method has no way to say "my copies" instead of just "copies". One parameter, always first, always called self, is the whole convention.
When should I use inheritance?
When the sentence "an X is a Y" is true and the child adds or changes a small part. An ebook is a book, so EBook inherits from Book. If the sentence is not true, do not force it: a library is not a book, so a Library class should hold books in a list, not inherit from Book.
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap