Python classes: build your own damn types
Updated · every example run on Python 3.9 to 3.15
With lesson 9 under your belt, a cat can live in a dictionary: {"name": "Tom", "weight": 4.2}. That works for one cat. By the twelfth cat, one of them has a "wieght", another has no weight at all, and the functions that feed them are scattered across three files. A class fixes that. It is a blueprint for a kind of thing: what data each one carries and what it can do.
You've been using objects since lesson 1. Every string is an object of the class str, and "meow".upper() is a method call on it. Now you get to make your own classes, and your own bugs to go with them.
A class and its init
class Cat:
def __init__(self, name, weight):
self.name = name
self.weight = weight
tom = Cat("Tom", 4.2)
luna = Cat("Luna", 3.8)
print(tom.name, tom.weight)
print(luna.name, luna.weight)
print(type(tom))Tom 4.2
Luna 3.8
<class '__main__.Cat'>class Cat: starts the blueprint. Class names use CapitalizedWords, which is a convention, not a rule, but everyone follows it. Calling Cat("Tom", 4.2) makes a new object, an instance of Cat, and Python immediately runs __init__ on it. That's "init" with two underscores on each side, pronounced "dunder init" by people who are tired of saying "double underscore".
self is the brand-new object. self.name = name sticks a value onto it, and a value stuck onto an object is an attribute. You never pass self yourself: Python fills it in, and your arguments go in the slots after it. Leave one out, as in Cat("Tom"), and you get TypeError: missing 1 required positional argument, naming 'weight'. Since 3.10 the message says Cat.__init__(); 3.9 only says __init__(), which is less helpful when you have forty classes.
Note type(tom): your class is a type now, just like str and int. The __main__ in front is the module it lives in, from lesson 12.
Methods: functions that know their object
A method is a function defined inside a class. Its first parameter is self, the object it was called on, so it can read and change that object's attributes:
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError(f"{self.owner} can't afford {amount}")
self.balance -= amount
account = BankAccount("Sam", 100)
account.deposit(50)
account.withdraw(30)
print(account.owner, "has", account.balance)
BankAccount.deposit(account, 5)
print(account.owner, "has", account.balance)
try:
account.withdraw(1000)
except ValueError as error:
print("Nope:", error)
print(account.owner, "still has", account.balance)Sam has 120
Sam has 125
Nope: Sam can't afford 1000
Sam still has 125Here is the whole damn secret of self, in one line: account.deposit(50) is the same call as BankAccount.deposit(account, 50). Python takes the object before the dot and passes it as the first argument. The second line of output proves it: the long way deposits five dollars like the short way does.
The withdraw method refuses to go below zero with raise, from lesson 10. Because it raises before it subtracts, the failed withdrawal leaves the balance alone. The bank of Sam is fiscally responsible, which is more than can be said for Sam.
And yes, self is only a name. The Python tutorial itself says it has no special meaning to Python. Call it this or me and the code still runs, and every Python programmer who reads it will wince for reasons they can't fully explain. Use self.
Attributes on the class, attributes on the object
An attribute set through self belongs to one object. A variable written directly in the class body belongs to the class, and every object shares it. That's fine for a constant, and a disaster for a list:
class Dog:
species = "Canis familiaris"
tricks = []
def __init__(self, name):
self.name = name
def learn(self, trick):
self.tricks.append(trick)
rex = Dog("Rex")
fido = Dog("Fido")
rex.learn("sit")
fido.learn("play dead")
print(rex.name, fido.name, rex.species)
print(rex.tricks)
print(fido.tricks)Rex Fido Canis familiaris
['sit', 'play dead']
['sit', 'play dead']Rex learned to play dead without lifting a paw. There is exactly one tricks list, on the class, and both dogs append to it. species is shared too, but nobody changes it, so that's what you want. The fix for the list is to give each dog its own, in __init__:
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
self.tricks = []
def learn(self, trick):
self.tricks.append(trick)
Rule of thumb: anything that differs from one object to the next, and anything you're going to change, gets created in __init__ with self..
str and repr: make print say something
Print a Cat from the first section and Python shows the class name and a memory address, which is Python's way of saying "it's an object, good fucking luck". Two special methods fix that:
class Cat:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __str__(self):
return f"{self.name}, {self.weight} kg of attitude"
def __repr__(self):
return f"Cat({self.name!r}, {self.weight!r})"
tom = Cat("Tom", 4.2)
luna = Cat("Luna", 3.8)
print(tom)
print(f"Today's cat: {luna}")
print(repr(tom))
print([tom, luna])Tom, 4.2 kg of attitude
Today's cat: Luna, 3.8 kg of attitude
Cat('Tom', 4.2)
[Cat('Tom', 4.2), Cat('Luna', 3.8)]__str__ is for humans: print(), str() and f-strings use it. __repr__ is for programmers: repr(), the interactive prompt, and anything inside a list or dictionary use it. That's why the list on the last line shows the repr of each cat, not the friendly version. A good __repr__ looks like the code that would make the object again. The !r inside the f-string means "use the repr of this value", which is what puts the quotes around 'Tom'.
Both methods must return a string, not print one. If you only write one, write __repr__: when a class has no __str__, print falls back to __repr__.
Forget self in the def
This is the mistake everybody makes in their first week, usually more than once:
class Cat:
def __init__(self, name):
self.name = name
def meow():
print("Meow")
tom = Cat("Tom")
tom.meow()Traceback (most recent call last):
File "/home/me/project/main.py", line 9, in <module>
tom.meow()
~~~~~~~~^^
TypeError: Cat.meow() takes 0 positional arguments but 1 was given| Python | Prints |
|---|---|
| 3.9 | TypeError: meow() takes 0 positional arguments but 1 was given |
| 3.10–3.15 | TypeError: Cat.meow() takes 0 positional arguments but 1 was given |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
You called tom.meow() with no arguments, and Python says one was given. It's counting the one it passed for you: tom, as self. The method has no parameter to receive it, so the call fails. Since 3.10 the message names the method as Cat.meow(); 3.9 just says meow(). Either way, the fix is to add self as the first parameter. More on this message on the page TypeError: takes 0 positional arguments but 1 was given.
Forget self. in the body
The sequel, starring the same cat. This time self is in the parameters, but not in front of the attribute:
class Cat:
def __init__(self, name):
self.name = name
def introduce(self):
print("I am", name)
tom = Cat("Tom")
tom.introduce()Traceback (most recent call last):
File "/home/me/project/main.py", line 9, in <module>
tom.introduce()
~~~~~~~~~~~~~^^
File "/home/me/project/main.py", line 6, in introduce
print("I am", name)
^^^^
NameError: name 'name' is not defined. Did you mean: 'self.name'?| Python | Prints |
|---|---|
| 3.9–3.11 | NameError: name 'name' is not defined |
| 3.12–3.15 | NameError: name 'name' is not defined. Did you mean: 'self.name'? |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Inside a method, name is just a variable, and there isn't one. The cat's name lives on the object, so you have to go through it: self.name. That's a NameError: name is not defined. Python 3.12 and later notice that the object has an attribute with that name and add "Did you mean: 'self.name'?" to the message, which is about as close as an interpreter gets to rolling its eyes. Up to 3.11, you get the bare NameError.
The scarier version has no error at all: if a global variable called name happens to exist, the method quietly prints that instead. Wrong cat, no traceback, one hell of a long evening.
Try it yourself
Write a class ShoppingList that starts empty, has a method add(item), a method count() that returns how many items there are, and a __str__ that joins the items with commas. Then add eggs and coffee, and print the list and the count. One new tool: ", ".join(items) glues a list of strings into one string, with ", " between them.
Show the answer
class ShoppingList:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def count(self):
return len(self.items)
def __str__(self):
return ", ".join(self.items)
groceries = ShoppingList()
groceries.add("eggs")
groceries.add("coffee")
print(groceries)
print(groceries.count(), "items")
The list is created in __init__ with self.items, so every ShoppingList gets its own. It prints eggs, coffee and then 2 items.
Questions
What is self in Python?
self is the object a method was called on. Python passes it automatically as the first argument, so tom.meow() runs Cat.meow(tom). The name is a convention; the position is what matters.
What is the difference between str and repr in Python?
__str__ is the readable version that print and f-strings show. __repr__ is the unambiguous one, used by repr(), by lists and dictionaries, and by print when there is no __str__.
What does init do in a Python class?
It sets up a new object right after Python creates it, usually by storing the arguments as attributes on self. It runs automatically every time you call the class, and it must not return anything but None.
When should I use a class instead of a dictionary?
When the same kind of thing shows up many times with the same fields and the same actions. A dictionary is fine for one bag of data; a class sets the same attributes on every object in one place, __init__, and keeps the functions that use them next to the data.
Sources
- Classes, Python documentation
- Data model: basic customization, Python documentation
- Built-in functions: repr, Python documentation
- What's New in Python 3.12: improved error messages, Python documentation
- PEP 8: class names, Python Enhancement Proposals
Read on November 11, 2026.