Template and instance
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
Dog describes what a dog looks like: it has a name and an age. Dog("rex", 3) builds one specific dog. Build two and they are independent. Changing a.age leaves b.age alone. Each instance carries its own set of attributes.
A class is a template. An instance is a thing built from that template. You use classes whenever you have a group of values that belong together and a set of actions that operate on them. A point has an x and a y. A bank account has a balance, a deposit method, and a withdrawal method. A student has a name, a list of grades, and a method that computes the average. In every case, the class bundles the data and the behavior into one unit.
Without classes, you would use plain dictionaries or tuples to group related values. That works for simple cases, but it has no structure. Nothing stops you from misspelling a key, forgetting a field, or passing the wrong dictionary to a function. A class gives you a constructor that enforces the shape. If Dog.__init__ expects a name and an age, calling Dog("rex") raises a TypeError immediately instead of failing silently later.
Methods are functions defined inside the class body. The first parameter is always self, which refers to the specific instance the method was called on. When you write a.bark(), Python passes a as self automatically. This is how each dog can have its own name but share the same method definition.
The __init__ method runs automatically when you create an instance. It is where you set up the initial state. Every attribute you want the instance to carry should be assigned to self in __init__. Attributes created anywhere else are harder to find and easier to forget.
This page covers defining a class, writing __init__, creating instances, adding methods, and the relationship between a class and the objects it produces.
What __init__ does
__init__ runs right away after the instance is created. Its job is to set up that instance's data. It isn't a constructor in the C++ sense. The object already exists by the time it runs. But it's where you put all the object needs to start life.
The double underscores mark it as a name Python itself calls. You almost never call __init__ right.
self is not magic
self is the instance, handed to the method as its first arg. Python does this for you: a.speak() is Dog.speak(a). The page prints both to show they're the same call.
The name self is rule rather than syntax. The first param could be called any of it. But each Python programmer expects self. Using a thing else will read as a mistake.
each method that touches instance data needs it. Each field belonging to the instance is reached through it. Losing self. inside a method is the most common early error. You get a local variable that vanishes when the method returns.
Class attributes are shared
class Counter:
total = 0 # one, for everybody
def __init__(self):
self.count = 0 # one per instance
self.count belongs to the object. Counter.total belongs to the class and each instance sees the same one. This is at times what you want. A registry, a shared cache, a constant. And is a bug the rest of the time, in the same family as the mutable default arg.
By default, printing an object gives you a thing like <__main__.Point object at 0x104...>. This Tells you nothing. Define __repr__ and you decide:
def __repr__(self):
return f"Point({self.x}, {self.y})"
It costs two lines and pays for itself the first time you print a list of them.
When a class is the right answer
Not all should be a class. Python isn't a language where you've to wrap a function in one to run it. A module full of functions is a just right good design.
The signal that you want a class is data and action travelling together. If a few functions all take the same three args, and those three args always change as a group, they're showing one thing that doesn't have a name yet. Giving it a name and hanging the functions off it as methods drops the repetition and makes the tie clear.
The opposite signal is a class with one method and no state beyond what that method was passed. That is a function wearing a costume, and the function is easier to test, easier to import and easier to read.
State is the thing to be careful with
An object's fields are its state, and state is what makes code harder to reason about, because the answer to "what does this method return" turns "it depends what happened earlier". That isn't an arg against classes. It's an arg for keeping state small and obvious.
Two habits help. Set each field in __init__, even if only to None, so that reading the constructor tells you all the object holds - fields appearing halfway through some other method are how objects become mysterious. And prefer methods that return new values over methods that quietly mutate the object, unless mutation is the point and the name says so.
The underscore convention
Python has no private fields. A leading underscore - self._cache - is a rule meaning "this is inner, don't lean on it", and nothing enforces it. That sounds weak and works oddly well: it marks the boundary between what you promise and what you may change. This Is all the gap was ever for.
A double leading underscore triggers name mangling. This Is a different feature aimed at avoiding clashes in subclasses rather than at privacy. It's rarely what you want.
Dataclasses, for when it is mostly data
If a class exists chiefly to hold fields, the standard library will write the boilerplate:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
That gives you __init__, a readable __repr__ and equality check for free, which is three of the things you'd or else write by hand and one - __repr__ - that people often skip and then miss the first time they print a list of them.
A small class, end to end
All a plain class often needs, in one block:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError(f"deposit must be positive, got {amount}")
self.balance += amount
return self.balance
def __repr__(self):
return f"Account({self.owner!r}, {self.balance})"
def __eq__(self, other):
if not isinstance(other, Account):
return NotImplemented
return (self.owner, self.balance) == (other.owner, other.balance)
a = Account("ana")
a.deposit(50)
print(a)
print(a == Account("ana", 50))
try:
a.deposit(-5)
except ValueError as e:
print("ValueError:", e)
Account('ana', 50)
True
ValueError: deposit must be positive, got -5
Four things earn their place. each field is set in __init__, so reading it tells you all the object holds. The method validates its input and says what it received, not just that a thing was wrong. __repr__ uses !r on the owner so strings print quoted. This Is what makes a repr unambiguous. And __eq__ returns NotImplemented — not False — for unrelated types, which lets Python try the other object's check before giving up.
The dunder methods worth knowing
Python's protocols are all spelled as double-underscore methods, and defining them is how your class gets to behave like a built-in type. Six cover most needs.
__repr__ is for programmers and should ideally look like the code that would recreate the object. __str__ is for users. If you only write one, write __repr__, because str() falls back to it and the interactive prompt and containers use it even so.
__eq__ decides what equality means. Define it and you almost always want __hash__ too, because a class that defines __eq__ without __hash__ turns unhashable and can't go in a set or be a dict key. The pair must agree: objects that compare equal must hash the same.
__len__ gives len() and, as a side effect, truthiness. __iter__ makes the object work in a for loop, in unpacking, and in list(). __contains__ gives in, though __iter__ alone gives a working fallback.
The rest — math operators, context managers, checks — follow the same idea: Python asks the object, and the object answers by having the method. There's no separate interface to declare. A dataclass writes __init__, __repr__ and __eq__ for you. This Is three of the six and the usual reason to reach for one.
Properties, for when an attribute needs logic
Python has no tradition of writing get_x() and set_x() for each field, because it doesn't need one. Fields start as plain fields, and if one later needs validation or work, @property converts it without changing a single call site.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return 3.14159 * self.radius ** 2
c.area is now found on access and written without brackets, so it reads like data. A matching @area.setter would let it be assigned, often to validate: raising on a minus radius at the moment it's set rather than discovering it later in a math.
The key consequence is cultural. In languages where adding validation means changing each caller, people write accessors for all up front, just in case. In Python that insurance is unneeded, so the idiomatic style is a plain field until the day it needs to be more. And the day it does, nothing outside the class changes.
Use a property when the value is truly field-like: cheap, side-effect free, and conceptually part of the object's state. If it does real work, makes a network call, or can fail in notable ways, a method with brackets is honest about that and a property isn't.
What makes a class worth reading
The mechanics of a class are simple. The judgement is in what goes on it, and a few habits separate classes people can use from classes people work around.
One job, named. If the class name needs "and" to show it, it is two classes. A name that is a noun for a thing in the problem — Invoice, Link, Basket — is a better sign than one built from patterns, like InvoiceManager or DataHandler, which often means "some functions I put a place".
A small surface. The methods a caller needs should be few and obvious, and all else should carry a leading underscore. A class with twenty public methods is asking its callers to learn twenty things, and most of them often turn out to be steps of two or three real ops.
Fields that are all set in one place. __init__ should establish each field the object will ever have. Fields that appear halfway through another method make the object's state depend on call order, which is just the thing that turns into "it works if you call load() first".
**Methods that use self.** A method that never touches the instance is a function that has been filed in the wrong place. Moving it out makes it testable on its own and shortens the class.
The underlying question is whether the class makes calling code shorter and clearer than the equal functions would. If it doesn't, the functions were the right answer, and Python is just right happy with a module full of them.
Testing one
A class is easy to test when its state is small and its methods return values, and hard when it's neither — which makes testability a handy design signal rather than a separate chore.
The straightforward shape is: make the object, call a method, assert on what came back or on one field. If that is awkward, the reason is often one of three things. The constructor does real work, such as opening a file or making a request, so the object can't be built in a test without the outside world. The fix is to take the link as an arg rather than creating it. The method returns nothing and changes a few fields, so the assertion has to know internals. The fix is often to return the result. Or the outcome depends on what was called earlier, in which case the test has to replay a sequence, and that is the sign that the state wants to be smaller.
__eq__ earns its place here too: it lets a test compare a whole object against an expected one in a line, instead of asserting on four fields and missing the fifth.
Questions people ask about Classes and Objects
Why does each method need self? Because a.speak() is Dog.speak(a) — the instance is passed by name rather than appearing by magic. Python prefers clear.
What is the difference between a class and an instance field? A class field is one object shared by all. An instance field belongs to one object. set always creates the instance one.
Do I need getters and setters? No. Use plain fields, and @property on the day one needs logic.
What is __slots__? A declaration of the allowed fields that saves memory for classes with many instances, at the cost of losing dynamic fields. Worth it rarely.
Should I write __str__ or __repr__? __repr__ first — it's what containers and the prompt use, and str() falls back to it.
What is a @staticmethod for? A function that belongs with the class conceptually but uses neither the instance nor the class. A module function is often just as good.
Why does my object print as an address? Because it has no __repr__. Two lines fix it permanently.
Can a class have no methods at all? Yes, and a dataclass with only fields is a just right good way to give a group of related values a name and a readable repr.
Classes and Objects: recap in one screen
- A class bundles data with the functions that operate on it. Each instance carries its own fields and shares the methods.
- Set each field in
__init__. So Reading the constructor tells you what the object holds. self is the instance, passed by name — a.f() is Cls.f(a).- Class fields are shared by each instance. Set through
self always creates an instance field instead. __repr__ costs two lines and pays for itself the first time you print a list of them. A dataclass writes it, __init__ and __eq__ for you.