Turn a book into an object and its rules into a class: Python classes and objects
A class bundles data and its rules together: one Book class gives every book its own state, methods let objects do the work themselves, and inheritance lets an e-book stand on a paper book's shoulders. Following Chapter 9 of the official Python Tutorial: class and __init__, self, methods, class vs instance variables, attribute lookup, inheritance and overriding, super(), the underscore-private convention, dataclasses, __iter__ and __next__ — plus a 100-accident chart.

First, the boundaries of this guide. This is the third guide in the "Python Basics" series, continuing from the first two: the first covered storing numbers, text, and lists in variables, and using if, for, and while to let a program decide things and repeat work; the second covered packing repeated work into functions and splitting files into modules. This one covers classes: how to bundle a bunch of related data together with the ways of working on it, making an "object"; and how to let new things inherit the abilities of old ones. Classes and exception handling are two different things: this guide only covers how classes make objects and how inheritance works, and exception handling gets the next guide. The example is still the fictional "Morning Light Bookstore": a small neighborhood bookstore whose owner wants a little Python bookkeeping script. By the end of the second guide, the script could work out the total stock value and give 10% off books over 50, using functions and dicts. The new problem in this guide is that there are more and more books, the dicts are getting scattered, and the rules for each book all have to be remembered by a person — which is easy to get wrong. Every statement about classes and objects comes from Chapter 9, "Classes", of the official Python Tutorial; sources are listed in each guide's meta information and evidence record. Every operation, code sample, and number built around the Morning Light Bookstore was made up to explain how things work; none of it is a real record. By the end of this guide you should be able to do four things: write a class with __init__ and make objects that keep their own state; tell class variables apart from instance variables and know where shared things belong; use inheritance to make new classes and know how method overriding works; and know when to use the underscore-private convention and handy tools like dataclasses and iterators.
Step 1: When do you need a class — a dict holds data, but not rules
First, where the bookstore script stands. In the first guide, a book was a dict: {'title': 'The Three-Body Problem', 'price': 59.0, 'stock': 7}; the discount was a function, the total stock value was a function, and selling a book and changing stock was a function. That works fine with three or five books, but as books pile up it breaks down: the rules for each book are scattered across functions, the discount rule lives in discounted_price(), the selling check lives in sell(), and the rule "stock must never go below zero" has to be written again everywhere stock changes. Miss one place and the books are wrong. My judgment is this: when you notice that "this data" and "the rules for this data" always show up together and never apart, it is time to put them in one place. That place is a class.
The first sentence of Chapter 9 of the official tutorial says exactly this: classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object; each class instance can have attributes attached to it for maintaining its state, and class instances can also have methods for modifying its state. In plain language: a class is a "how-to manual" plus a "factory machine"; each thing it makes is called an instance; each instance remembers its own numbers, and methods are the skills written in the manual that every instance knows. In the bookstore example: Book is the class, and the copy of "The Three-Body Problem" and the copy of "Twenty Thousand Leagues Under the Seas" are two instances; each book remembers its own title, price, and stock, and discounting and selling are skills every book knows.
One more sentence from the docs is worth remembering up front: compared with other programming languages, Python's class mechanism adds classes with a minimum of new syntax and semantics. In other words, classes are not mysterious: they are functions and dicts combined. When a class definition runs it builds a namespace, a method is a function written inside a class, and an attribute is a name hung on an object. The hard part of learning classes is not the syntax, but when to use them and where to put things. Most of this guide is about "where to put things".
Step 2: class and __init__ — first build a "factory mold"
The syntax for writing a class looks like this, in the simplest form given in section 9.3.1 of the tutorial:
class ClassName:
<statement-1>
.
.
.
<statement-N>
Like def, a class definition has to run before it takes effect; the statements inside the class body are usually function definitions, but other statements are allowed too. Entering a class definition creates a new namespace used as the local scope, and when the definition ends normally, a "class object" is created and bound to the class name. The simplest example in the tutorial looks like this:
>>> class MyClass:
... """A simple example class"""
... i = 12345
... def f(self):
... return 'hello world'
...
>>> MyClass.i
12345
>>> MyClass.f
<function MyClass.f at 0x...>
Class objects support two kinds of operations: attribute references and instantiation. MyClass.i is 12345, MyClass.f is a function object, and MyClass.__doc__ is that docstring. Instantiation uses function notation: x = MyClass() creates a new instance and hands it to x.
An empty object is not yet useful: every book in the bookstore should be born with a title, a price, and a stock. The tutorial calls this an "initial state", and the way to get it is a special method named __init__: when a class defines one, class instantiation automatically invokes it for the newly created instance. The tutorial's example is a complex number:
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
Complex(3.0, -4.5) passes its arguments straight to __init__, except for the first parameter, self. This is the first hurdle in understanding classes: who is self? It is "this instance itself". When you call x = Complex(3.0, -4.5), Python first creates an empty object, then passes that object into __init__ as self; self.r = realpart hangs an attribute named r on that object. My judgment is: read self as "myself" and it all falls into place — self.price = price means "remember the price that came in, on myself", and self.stock means "my own stock". It is only a conventional name; Python gives that name no special meaning at all, and the program would run the same with a different name — but anyone reading your code would struggle, so do not change it.
Written the same way, the bookstore's Book class looks like this:
class Book:
"""One book in the bookstore."""
def __init__(self, title, price, stock):
self.title = title
self.price = price
self.stock = stock
>>> book1 = Book('The Three-Body Problem', 59.0, 7)
>>> book2 = Book('Twenty Thousand Leagues Under the Seas', 39.5, 12)
>>> book1.title, book1.price, book1.stock
('The Three-Body Problem', 59.0, 7)
>>> book2.title, book2.price, book2.stock
('Twenty Thousand Leagues Under the Seas', 39.5, 12)
Two things to note. First, data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. Second, book1 and book2 each remember their own numbers without interfering with each other: changing book1.stock does not touch book2.stock. That is exactly the problem classes solve — every book keeps its own books.
Step 3: Methods — let the object do the work itself
The data is in place, but the rules still have nowhere to live. The discount rule "over 50 gets 10% off", working out the total stock value, selling books and reducing stock — all of these belong in methods, which are functions written inside a class. Section 9.3.4 of the tutorial gives one key equation for method calls: x.f() is exactly equivalent to MyClass.f(x). When a method is called, the instance object is inserted at the front of the argument list and passed in as the first argument. That is why a method definition writes self as its first parameter, but a call does not pass it — Python has already passed it for you.
A method object can also be stored away and called later: xf = x.f gives you a method object, and calling xf() afterwards has the same effect as x.f(). The bookstore script does not need that, but it shows one thing: a method is no magic, it is just "a function with one instance already bound to it".
Putting the rules into Book:
class Book:
"""One book in the bookstore."""
def __init__(self, title, price, stock):
self.title = title
self.price = price
self.stock = stock
def total_value(self):
"""The total value of this book's stock."""
return round(self.price * self.stock, 2)
def discounted_price(self):
"""10% off over 50, otherwise the original price."""
if self.price > 50:
return round(self.price * 0.9, 2)
return self.price
def sell(self, n):
"""Sell n copies; True if there are enough, False if not."""
if n > self.stock:
return False
self.stock -= n
return True
>>> book1 = Book('The Three-Body Problem', 59.0, 7)
>>> book1.total_value()
413.0
>>> book1.discounted_price()
53.1
>>> book1.sell(2)
True
>>> book1.stock
5
>>> book1.sell(99)
False
>>> book1.stock
5
Check the numbers: "The Three-Body Problem" at 59.0 times 7 copies is 413.0; 59.0 is over 50, so 10% off gives 53.1; selling 2 leaves 5; trying to sell 99 is not enough, so it returns False and the stock stays at 5 — not a single copy lost. My judgment is: there is only one thing that is easy to get wrong inside a method, and that is forgetting self. — writing price inside a method means a local variable, while self.price means "my own price". Section 9.4 of the tutorial makes a point of this too: there is no shorthand for referencing data attributes from within methods, and that actually makes methods more readable, because at a glance you can tell which names belong to the instance and which are local.
Methods can also call other methods, using self to call them: the tutorial's Bag example does exactly this, with addtwice calling self.add(x) twice. The bookstore could add a "checkout" method that calls self.discounted_price() internally and multiplies by the quantity, instead of writing the discount rule a second time. A rule written in one place only has to be changed in one place — that is the benefit of "packing it away" from step one.
Step 4: Class variables vs instance variables — shared by the whole store, or unique to each book
An assignment written directly in the class body and an assignment written in __init__ starting with self. are two different things. Section 9.3.5 of the tutorial puts it this way: generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class. The tutorial's example is a dog:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
kind is a class variable: every dog shares one "canine". name is an instance variable: each dog's own name. The bookstore is the same: the store name is shared by the whole store, while title, price, and stock belong to each book.
class Book:
store = 'Morning Light Bookstore' # class variable, shared by the store
def __init__(self, title, price, stock):
self.title = title
self.price = price
self.stock = stock
>>> book1 = Book('The Three-Body Problem', 59.0, 7)
>>> book2 = Book('Twenty Thousand Leagues Under the Seas', 39.5, 12)
>>> book1.store, book2.store
('Morning Light Bookstore', 'Morning Light Bookstore')
>>> Book.store
'Morning Light Bookstore'
A class variable can be read from the class or from an instance. But here is the biggest trap for beginners, which the tutorial explains twice with the same dog: never use a mutable object — a list or a dict — as a class variable. Watch this:
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']
Fido only learned to roll over and Buddy only learned to play dead, yet d.tricks contains both: because there is only one tricks list, shared by all dogs, and anything anyone appends to it is visible to everyone. The correct design puts the list in __init__, so each dog gets a fresh empty list at birth:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']
The bookstore version: each book's "sales record" must go in __init__ as self.sales = []. Written as a class variable sales = [], the sales of "The Three-Body Problem" would show up under "Twenty Thousand Leagues Under the Seas" and the books would be a mess. My judgment is: this rule can be memorized as one sentence — things that never change (the store name, the discount rate, the tax rate) go in class variables, and things that change (lists, dicts, each book's own numbers) always go in __init__ hung on self.. When in doubt, default to __init__; you cannot go wrong that way.
Step 5: Attribute lookup — the instance wins, then the class is searched
When you write book1.store, where does Python actually look? Section 9.4 of the tutorial gives the answer: if the same attribute name occurs in both an instance and in a class, then attribute lookup prioritizes the instance. The tutorial's example is a warehouse:
>>> class Warehouse:
... purpose = 'storage'
... region = 'west'
...
>>> w1 = Warehouse()
>>> print(w1.purpose, w1.region)
storage west
>>> w2 = Warehouse()
>>> w2.region = 'east'
>>> print(w2.purpose, w2.region)
storage east
w2.region = 'east' did not change the class's region; it only created a same-named attribute on the w2 instance that "covers" the class one. w1.region is still 'west', and Warehouse.region itself is still 'west'. The bookstore version:
>>> book1 = Book('The Three-Body Problem', 59.0, 7)
>>> book2 = Book('Twenty Thousand Leagues Under the Seas', 39.5, 12)
>>> book1.store
'Morning Light Bookstore'
>>> book2.store = 'Morning Light Bookstore, Branch'
>>> book1.store
'Morning Light Bookstore'
>>> book2.store
'Morning Light Bookstore, Branch'
>>> Book.store
'Morning Light Bookstore'
This lookup rule also explains how methods are found: book1.discounted_price is first looked up on the instance; not found there, it is looked up in the Book class, where a function object is found and the instance is bound to it to make a method object. Method lookup and attribute lookup walk the same road.
Two more things the tutorial points out. First, data attributes may be referenced by methods as well as by ordinary users of an object; nothing in Python makes it possible to enforce data hiding — it is all based upon convention. In other words, classes are not usable to implement pure abstract data types: anyone using the class can stamp directly on an instance's attributes and break the rules the methods maintain, and nobody stops them. Remember that sentence; step eight comes back to it. Second, clients may add data attributes of their own to an instance object at any time: book1.note = 'Owner recommends' adds a note to that one book without affecting other objects or the class. Flexible, yes — but my judgment is: do not live on this feature. Attributes should be hung in one go inside __init__; code that hangs attributes halfway through reads like a guessing game.
Step 6: Inheritance — a new kind of book standing on the old kind's shoulders
The bookstore is going to sell e-books. An e-book has the same title, price, and stock as a paper book, the same total stock value, and the same over-50 discount — except it also has a file size, and its discount is different: e-books get 20% off. Copying Book and editing the copy would work, but the next time the discount rule changes it would have to change in two places, and we are back to the problem from step one. Section 9.5 of the tutorial offers inheritance:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
When a derived class definition runs, the base class is remembered. Attribute references are resolved by searching the class first and then the base class, applied recursively if the base class is itself derived from another class. There is nothing special about instantiating a derived class: DerivedClassName() creates a new instance of the derived class. Derived classes may override methods of their base classes — and because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. In the tutorial's words to C++ programmers: all methods in Python are effectively virtual.
class EBook(Book):
"""An e-book: it inherits every paper-book rule, changes only the
discount, and adds a file size."""
def __init__(self, title, price, stock, file_size_mb):
super().__init__(title, price, stock)
self.file_size_mb = file_size_mb
def discounted_price(self):
"""E-books get 20% off."""
return round(self.price * 0.8, 2)
>>> ebook = EBook('The Three-Body Problem', 59.0, 7, 12.5)
>>> ebook.title, ebook.file_size_mb
('The Three-Body Problem', 12.5)
>>> ebook.total_value()
413.0
>>> ebook.discounted_price()
47.2
>>> ebook.sell(1)
True
>>> ebook.stock
6
Check the numbers: the e-book of "The Three-Body Problem" at 59.0 with 20% off is 47.2; total_value() and sell() are inherited from Book and work without being rewritten, so the total stock value is still 413.0; selling 1 leaves 6. The super().__init__(title, price, stock) in __init__ says: "let the parent class run its own setup first", and then I add my own file_size_mb. Forgetting to call the parent's __init__ means title, price, and stock never get created at all, and the first use raises AttributeError — one of the most common subclass mistakes, and it is in the chart in step ten.
Sometimes an overriding method wants to extend the base class method rather than simply replace it. The tutorial's way is to call the base class method directly: BaseClassName.methodname(self, arguments). For example, a sale e-book could be "the paper-book 10% off first, then 5 off on top":
class EBookSale(EBook):
"""A sale e-book: 10% off like a paper book, then 5 off."""
def discounted_price(self):
return round(Book.discounted_price(self) - 5, 2)
>>> ebook2 = EBookSale('The Three-Body Problem', 59.0, 7, 12.5)
>>> ebook2.discounted_price()
48.1
59.0 at 10% off is 53.1, minus 5 is 48.1. In real code the more common spelling is super().discounted_price(), which does the same thing; the tutorial mentions it when it talks about cooperative super() calls in the multiple-inheritance section. My judgment is: before overriding a method, first ask one question — "am I replacing the parent's behavior, or adding to it?" If it is the latter, call the parent's method once instead of copying its logic again.
Finally, two built-in tools the tutorial provides for working with inheritance: use isinstance() to check an instance's type — isinstance(obj, int) is True only if obj.__class__ is int or some class derived from int — and use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int, while issubclass(float, int) is False. The bookstore version:
>>> isinstance(ebook, EBook)
True
>>> isinstance(ebook, Book)
True
>>> isinstance(book1, EBook)
False
>>> issubclass(EBook, Book)
True
>>> issubclass(bool, int)
True
An e-book is both an EBook and a Book, but a paper book is not an e-book. That sounds like a tongue-twister, but it is exactly what inheritance means: a subclass object can stand in everywhere the parent class is used.
Step 7: Multiple inheritance and super() — know it exists, do not rush to use it
Python allows a class to inherit from several base classes, written as class DerivedClassName(Base1, Base2, Base3):. Section 9.5.1 of the tutorial says that, for most purposes, you can think of the search for inherited attributes as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy — but in fact the method resolution order is slightly more complex than that, changing dynamically to support cooperative calls to super(). My judgment is: at the beginner stage, knowing "it exists, lookup runs left to right, and super() lets several parents' setup cooperate" is enough. Multiple inheritance is rare in real projects and easy to tangle up. The bookstore script does not need it; one inheritance chain from paper book to e-book is plenty. If the day comes when a class really must inherit from two things, draw the inheritance diagram first and print ClassName.__mro__ to look at the resolution order before writing code.
super() itself deserves one more sentence. The super().__init__(title, price, stock) in step six is its most common use: the subclass asks the parent class to do the parent's part of the setup first. But super() is not just a shorthand for "call the parent": it follows the method resolution order to find the next class, so in multiple inheritance it lets each parent's setup run exactly once — no more, no less. With single inheritance, super().method() and BaseClass.method(self) do the same thing; with multiple inheritance the former is steadier. At the beginner stage, remember one habit — "in a subclass __init__, call super().__init__() first" — and you will rarely go wrong.
Step 8: The private convention — an underscore is an agreement, not a lock
Step five left a loose end: "private" instance variables that cannot be accessed except from inside an object do not exist in Python. Section 9.6 of the tutorial opens with exactly that sentence, then gives the convention: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API, whether it is a function, a method, or a data member. It should be considered an implementation detail and subject to change without notice. In plain language: the underscore is a "staff only" sign on the door, not a lock. You can push the door open if you insist, but do not blame anyone else if something breaks.
The bookstore version: a book's cost price is not something outsiders should change at will, so write it as self._cost_price and offer a read-only method cost_price() to look at it. Anyone who sees the underscore knows "do not change this directly" — and Python will not stop them if they do.
Names with two leading underscores (e.g. __spam — at least two leading underscores, at most one trailing underscore) get one more layer, called "name mangling": the identifier is textually replaced with _classname__spam, where classname is the current class name with leading underscores stripped. The tutorial says mangling is helpful for letting subclasses override methods without breaking intraclass method calls, and that the mangling rules are designed mostly to avoid accidents — it is still possible to access or modify a variable that is considered private. The tutorial's example is a Mapping class:
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
The subclass changes update's signature to take keys and values; but the parent's __init__ calls self.__update, which is _Mapping__update, while the subclass rewrites _MappingSubclass__update — the two do not collide, and the parent's setup still runs. Check the numbers:
>>> m = Mapping([1, 2, 3])
>>> m.items_list
[1, 2, 3]
>>> s = MappingSubclass([1, 2, 3])
>>> s.items_list
[1, 2, 3]
>>> s.update(['a', 'b'], [10, 20])
>>> s.items_list
[1, 2, 3, ('a', 10), ('b', 20)]
My judgment is: in everyday code, only the single-underscore convention is needed; double-underscore mangling only earns its keep when you write a base class that others will inherit from and you worry about a subclass method colliding by name. When you see a double underscore, do not panic — it is not encryption, just a class name added as a prefix.
Step 9: dataclasses — for a class that only holds data, stop hand-writing __init__
Some classes have no real behavior; they just bundle a few named data items together. Section 9.7 of the tutorial says the idiomatic approach for this "Pascal record" or "C struct" shape is to use dataclasses. The tutorial's example is an employee:
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
salary: int
>>> john = Employee('john', 'computer lab', 1000)
>>> john.dept
'computer lab'
>>> john.salary
1000
One decorator, @dataclass, writes __init__ for you, and throws in a readable repr and equality by field for free. The bookstore can use one for a "restock order":
from dataclasses import dataclass
@dataclass
class Restock:
title: str
count: int
cost: float
>>> order = Restock('The Three-Body Problem', 10, 45.0)
>>> order
Restock(title='The Three-Body Problem', count=10, cost=45.0)
>>> order.count * order.cost
450.0
10 copies at 45.0 is 450.0. My judgment is: telling a "data class" apart from a "behavior class" is the key point — Restock, which only records numbers and occasionally multiplies them, takes a dataclass; Book, which has to manage discounts, selling, and stock rules, is written as a plain class with methods. The reverse is just as wrong: stuffing a dataclass with methods, or hand-writing a long data-only __init__ for a plain class, is heading the wrong way.
Step 10: Letting an object work in a for loop — __iter__ and __next__, plus a chart of mistakes
Section 9.8 of the tutorial covers iterators: behind the scenes, the for statement calls iter() on the container object, which returns an iterator object that defines the method __next__() to access elements one at a time; when there are no more elements, __next__() raises a StopIteration exception, which tells the for loop to terminate. The tutorial's example is a Reverse class that loops over a sequence backwards:
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x...>
>>> for char in rev:
... print(char)
...
m
a
p
s
Notice a raise StopIteration appears here: a class can raise an exception on purpose, and exception handling is the next guide's topic — for now just look at the shape of it. __next__() uses a raised exception to tell the for loop "there is no next one". The bookstore can make a "shelf" class that works in a for loop:
class Shelf:
"""A shelf holding a few books, which a for loop can take out one by one."""
def __init__(self, books):
self.books = books
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.books):
raise StopIteration
book = self.books[self.index]
self.index += 1
return book
>>> shelf = Shelf([Book('The Three-Body Problem', 59.0, 7), Book('Twenty Thousand Leagues Under the Seas', 39.5, 12)])
>>> [b.title for b in shelf]
['The Three-Body Problem', 'Twenty Thousand Leagues Under the Seas']
Section 9.9 adds one more note: generators (using yield) make iterators even more cheaply, with __iter__ and __next__ created automatically. This guide does not go into generators — that is for later. Knowing that "a class can become something a for loop can use, with two special methods" is enough. By the way, names with two underscores on each side like __init__, __iter__, and __next__ are called "special methods" or "magic methods": Python calls them automatically on particular occasions. You do not have to memorize the whole table; learn each one when you need it.
Finally, the mistake chart for this guide. Example: the fictional Morning Light Bookstore bookkeeping script in its third month of learning Python, 100 class-and-object mistakes, broken down by cause. The top two mistakes in the chart are both "things put in the wrong place": forgetting to write self, or putting something that belongs on an instance onto the class.

Looking back over the ten steps, this guide really only taught three things. First, a class is a way of putting data and rules in one place: __init__ makes sure every instance is born with its own state, and methods are the skills written in the class that every instance knows. Second, where things go matters: shared things go in class variables, unique things go in __init__, and a mutable list must never go in a class variable; lookup favors the instance and falls back to the class. Third, inheritance means "standing on the shoulders of the old thing": a subclass takes everything from its parent and changes only the part that differs, and forgetting to call the parent's __init__ is the most common trap. The next guide covers exception handling: when a program crashes, how to catch the error, how to stop it yourself, and how to make sure the cleanup always runs. Classes and exceptions are two independent skills — but the next guide's custom exceptions are themselves written with classes, so when you get there you will find these two guides are two sides of the same thing.
Comments (0)
Sources
Related articles
An exception is not a broken program: it is Python telling you what went wrong, with a name you can catch. Following Chapter 8 of the official Python Tutorial: syntax errors vs exceptions, try/except, matching by inheritance, which errors to catch and which to leave alone, raise, else, finally, with, user-defined exceptions, chaining, and ExceptionGroup — plus a 100-accident breakdown from a fictional bookstore script.
A function packs repeated work into a name; a module packs definitions into a file you take out with import. Following Chapter 4 sections 4.8-4.9 and Chapter 6 of the official Python Tutorial: def and return, local and global scope, defaults evaluated once, keyword arguments, *args and **kwargs, / and *, lambda, docstrings and annotations, the ways to import, the __main__ guard, packages and the search path — plus a 100-accident breakdown from a fictional bookstore script.
Variables are boxes for things, lists and dicts are boxes for lots of things, and if, for, and while let a program decide and repeat work on its own. Following Chapters 3-5 of the official Python Tutorial: division and the float quirk, string indexing and slicing, list assignment that never copies, dict get vs KeyError, truthiness, if/elif/else, for and range, while with break/continue/loop-else — plus a 100-accident breakdown from a fictional bookstore script.