Python Classes and Objects — __init__, Methods, Inheritance, and Dataclasses
A class is a way to keep related data and the code that works on that data in one place. This guide builds classes in small programs: a point class with a constructor and methods, the split between shared class attributes and per-object instance attributes, inheritance with a parent class and an override, the special methods that control how an object prints and compares, the dataclass form that writes the routine parts for you, and the property, class method, and static method forms that round out daily class work.
Written November 12, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: a class, a constructor, and methods
- Class attributes and instance attributes
- Inheritance: reuse, super, and overrides
- Special methods: printing and equality
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A class defines a new kind of object. The class holds attributes, which are the data, and methods, which are functions that work on that data. Each object built from the class is an instance of it, with its own set of attribute values. Two points can hold different coordinates and still be points, because the class fixes the shape and each instance fills in the values. Classes pay off when a program keeps many copies of the same shape, or when a shape gains behavior over time and the behavior belongs next to the data it reads.
The main program: a class, a constructor, and methods
The class keyword opens a class. The init method runs when a new object is built, and it sets up that object. The name self inside a method refers to the current object, and attributes are stored on it with a dot:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
def describe(self):
return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p.x, p.y)
print(p.describe())
p.move(1, -1)
print(p.describe())
q = Point(0, 0)
print(q.describe())
print(p.describe())
The exact output:
3 4
(3, 4)
(4, 3)
(0, 0)
(4, 3)
Calling Point(3, 4) builds a new object and passes 3 and 4 to init after self. The two stored values are then readable as p.x and p.y. A method call such as p.describe() passes p as self on its own, so the method line names one fewer argument than the call seems to give it. The move method changes the stored values in place, and the last two lines show the point of separate instances: q starts at the origin and stays there while p keeps its moved position. Each instance carries its own x and y, even though both share the one class definition.
Class attributes and instance attributes
A name set inside init on self belongs to one instance. A name set in the class body itself belongs to the class, and every instance reads the same value through it. The split matters most for values that can change. A list set in the class body would be shared by all instances, so a list that should belong to one object goes in init, where each new object gets a fresh one:
class Team:
kind = "work"
def __init__(self, name):
self.name = name
self.members = []
a = Team("alpha")
b = Team("beta")
print(a.kind, b.kind)
a.members.append("ana")
print(a.members, b.members)
Team.kind = "project"
print(a.kind, b.kind)
a.kind = "solo"
print(a.kind, b.kind, Team.kind)
The exact output:
work work
['ana'] []
project project
solo project project
The members list is per-instance, so adding a name to the first team leaves the second team empty. The kind string is shared, so changing it on the class changes what both teams read. The last block shows the lookup rule. Setting a.kind writes an instance attribute on that one object, which then hides the class value for that object only. The other team and the class itself still read the shared value. Code that wants one shared default and a few local overrides uses this rule on purpose. Code that sets a class name by accident on one instance gets a quiet split that is hard to spot later.
Inheritance: reuse, super, and overrides
A class can inherit from another class. The child class keeps the parent methods, can add its own, and can replace a parent method with its own version. The super call reaches the parent version of a method, which is how a child constructor sets up the part the parent owns:
class Shape:
def __init__(self, name):
self.name = name
def area(self):
return 0
def describe(self):
return f"{self.name} area {self.area()}"
class Square(Shape):
def __init__(self, side):
super().__init__("square")
self.side = side
def area(self):
return self.side * self.side
s = Square(5)
print(s.name, s.area())
print(s.describe())
print(isinstance(s, Shape), isinstance(s, Square))
base = Shape("blob")
print(base.describe())
The exact output:
square 25
square area 25
True True
blob area 0
Square inherits from Shape, so a square is a shape as well as a square, and isinstance reports both as true. The square replaces area with its own version, and that replacement is the one that runs, even when the caller is a parent method. The describe method lives on the parent, was never rewritten, and still calls the child area, which is why it prints 25 for the square and 0 for a plain shape. That late binding is the core of inheritance: shared code in the parent, varied steps in the child. It also sets the limit. A child that replaces most parent methods shares little, and two plain classes with a shared function often read better than a deep family tree.
Special methods: printing and equality
A name with double underscores on both sides is a special method. Python calls these methods from built-in operations, so a class can decide how it prints, how it compares, and more. Three of them cover most daily needs. The repr method returns a string for developers, the str method returns a string for readers, and eq decides when two objects count as equal:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
p = Point(3, 4)
print(repr(p))
print(str(p))
print(p)
print(p == Point(3, 4))
print(p == Point(3, 5))
print(p != Point(3, 5))
The exact output:
Point(3, 4)
(3, 4)
(3, 4)
True
False
True
The repr form names the class and shows the values in call form, so a reader could rebuild the object from the text. The str form is shorter and is the one print uses when no repr is asked for. If a class defines repr but not str, print falls back to the repr form. Equality is the sharper change. Without eq, two objects compare by identity, so two points with the same values would count as different. With it, value equality works, and the not-equal test is derived from it. A class that adds eq should think about hashing at the same time, because Python then sets the hash to none unless the class defines a hash method as well. For a mutable point that can move, staying unhashable is often the right call.
Dataclasses: the routine parts, written for you
Many classes do little more than hold values, take them in a constructor, print them, and compare them. The dataclass decorator writes that routine code from a list of typed fields. It adds a constructor, a repr, and value equality, in the order the fields are listed. A field with a mutable default needs the field helper, so each instance gets its own list:
from dataclasses import dataclass, field
@dataclass
class Book:
title: str
pages: int
tags: list = field(default_factory=list)
b = Book("Dune", 412)
print(b)
print(b == Book("Dune", 412))
b.tags.append("sf")
print(b.tags, Book("Dune", 412).tags)
@dataclass(frozen=True)
class Point:
x: int
y: int
pt = Point(1, 2)
print(pt)
try:
pt.x = 9
except Exception as e:
print(type(e).__name__)
The exact output:
Book(title='Dune', pages=412, tags=[])
True
['sf'] []
Point(x=1, y=2)
FrozenInstanceError
The book prints in the repr form and compares by value with no method written by hand. The tags default uses a factory, a function called for each new instance, so the first book can gain a tag while a new book still starts empty. A plain list as a default would fail at class definition time, for the same shared-mutable reason as the class attribute case above. The frozen form adds two things: setting an attribute after construction raises the error shown, and the object can be hashed. Frozen fits points, keys, and settings that should not drift after they are made. A normal class still wins when the object has real behavior, private state, or a constructor that does more than store its arguments.
Properties, class methods, and static methods
Three decorators cover the remaining daily forms. A property turns a method into an attribute read, so a value can be derived on access while callers keep the plain dot form. A class method receives the class as its first argument and suits alternate constructors. A static method is a plain function kept in the class because it belongs with it, and it receives neither the instance nor the class:
class Temp:
def __init__(self, celsius):
self._c = celsius
@property
def fahrenheit(self):
return self._c * 9 / 5 + 32
@classmethod
def from_fahrenheit(cls, f):
return cls((f - 32) * 5 / 9)
@staticmethod
def is_freezing(c):
return c <= 0
t = Temp(100)
print(t.fahrenheit)
t2 = Temp.from_fahrenheit(32)
print(t2._c, t2.fahrenheit)
print(Temp.is_freezing(0), Temp.is_freezing(5))
The exact output:
212.0
0.0 32.0
True False
The Fahrenheit read has no brackets, even though a method runs behind it. That shape lets a class store one unit and present the other, with no stored value to fall out of step. The class method builds an object from a different input form and uses the class argument to do it, so a subclass that inherits it builds the subclass, not the parent. The static method reads as a grouped helper: it tests a value and needs no state at all. Reach for these forms only when the plain form strains. A method that takes self and returns a value covers most needs, and a property that hides slow or failing work behind a plain read will surprise its callers.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Group data with the code that works on it | A plain class | The shape and its behavior stay in one place |
| Set up a new object | init on self | It runs at construction and stores per-instance values |
| Share one default across all instances | A class attribute | Every instance reads the same value through the class |
| Give each object its own list or dict | Set it in init | Each new object gets a fresh value, not a shared one |
| Reuse a parent and vary one step | Inheritance with an override | Shared code stays in the parent, the varied step in the child |
| Run parent setup from a child | super().init | The parent owns its part of the setup |
| Control how an object prints | repr and str | Repr serves developers, str serves readers |
| Compare objects by value | eq | Two objects with equal fields count as equal |
| Hold plain data with printing and equality | A dataclass | The decorator writes the constructor, repr, and equality |
| Make an object that never changes | A frozen dataclass | Writes raise an error and the object can be hashed |
| Present a derived value as a read | A property | Callers keep the dot form while a method runs |
| Build an object from another input form | A class method | It receives the class and builds that class |
| Group a helper that needs no state | A static method | It belongs with the class and receives neither argument |
Checklist
- Before storing a list or a dict on a class, set it in init instead, so each instance gets its own copy.
- Before writing a constructor, a repr, and equality by hand for a data-only class, use a dataclass and let the decorator write them.
- Before adding a parent class, name the code the child will truly share; a child that replaces most methods shares little.
- Before defining eq, decide whether the object should be hashable, and define a hash method or accept that it is not.
- Before hiding work behind a property, keep the work cheap and safe, because callers read it as a plain attribute.
- Before reaching for a class at all, try a plain function and a dict; a class earns its place when state and behavior belong together.
Related guides on this site
- Python Functions — def, Default Arguments, and Functions as Values — methods are functions whose first argument is the object itself.
- Python Lists, Dicts, and Sets — The Three Collections You Use Every Day — the collections that class attributes and instance attributes most often hold.
- Rust Structs and Enums — Named Fields, Variants, and match — the Rust form of grouping data, with methods on a struct and variants on an enum.
- C++ Classes and Objects — the C++ form of the same idea, with constructors, access control, and member functions.
Sources
- Python Tutorial, Classes — class definitions, class and instance attributes, inheritance, and the method forms.
- Python Standard Library, dataclasses — the dataclass decorator, fields and default factories, and frozen classes.
- Python Language Reference, Data Model — special method names, including repr, str, and eq.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.