Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. classes
13 min read

Classes & Objects

Everything in Python is an object: integers, strings, lists, functions, even modules. An object bundles some data with the operations that make sense on it, which is why you write line.split() and ports.append(80): split belongs to strings, and append belongs to lists. A class is the blueprint for a kind of object, and defining your own lets you keep related data and behavior together as a program grows past a single script.

This lesson builds one class, a 2D point of the kind every grid puzzle needs, and grows it step by step until it behaves like a built-in type.

Defining a Class

A class is defined with the class keyword. The special method __init__ runs whenever a new object is created, and sets up its starting data:

python
1class Point:
2    def __init__(self, x, y):
3        self.x = x
4

Calling the class like a function creates a new object, called an instance, and passes the arguments to __init__:

python
1p = Point(3, 4)
2p.x          # Return: 3
3p.y          # Return: 4

The first parameter of every method, conventionally named self, is the instance the method was called on. Python passes it automatically: Point(3, 4) creates a new object and calls __init__ with that object as self. Inside, self.x = x creates an attribute, a variable that belongs to that one instance. Each instance has its own attributes:

python
1a = Point(1, 2)
2b = Point(5, 6)
3a.x          # Return: 1

Class Attributes

A variable assigned in the class body, outside any method, is a class attribute: one value shared by every instance. It's a good place for constants that belong to the class:

python
1class Point:
2    DIRECTIONS = [(0, -1), (1, 0),
Mutable class attributes are shared
Because a class attribute is shared, a mutable one such as a list is shared too. If each instance needs its own list, create it in __init__ with self.items = []. Defining items = [] in the class body gives every instance the same list, and appending through one instance changes it for all of them. This is the same aliasing problem as with any shared list.

Methods

A method is a function defined inside a class. Methods take self first and use it to reach the instance's attributes:

python
1class Point:
2    def __init__(self, x, y):
3        self.x =

a.manhattan(b) is shorthand for Point.manhattan(a, b); the instance before the dot becomes self.

Class Methods and Static Methods

A method decorated with @classmethod receives the class itself, conventionally named cls, instead of an instance. Its most common use is an alternate constructor, a second way to create objects, such as parsing one from a string:

python
1class Point:
2    def __init__(self, x, y):
3        self.x = x

A method decorated with @staticmethod receives neither the instance nor the class. It's just a function that lives inside the class because it belongs there logically. In Python, a plain function at module level usually does the job just as well.

Properties

The @property decorator turns a method into something that reads like an attribute. It's useful for values computed from other attributes:

python
1class Point:
2    def __init__(self, x, y):
3        self.x = x
4

Python has no private keyword. By convention, a name starting with an underscore, such as self._cache, is internal to the class, and code outside it should leave it alone. Nothing enforces this; it's an agreement between programmers.

Special Methods

So far, printing a Point or comparing two of them gives unhelpful results:

python
1>>> p = Point(3, 4)
2>>> p
3<__main__.Point object at 0x7f3a2c1b9e50>

Python lets a class define how its instances behave with built-in operations through special methods, also called dunder methods for the double underscores around their names. __init__ is one. Python calls these for you: print(p) calls p.__str__(), a == b calls a.__eq__(b), and len(x) calls x.__len__().

Printing

__repr__ returns the unambiguous, developer-facing form of an object, which the REPL and debuggers show. Make it look like the code that would recreate the object. __str__ returns the friendly form that print() and str() use; if it isn't defined, Python falls back to __repr__:

python
1class Point:
2    def __init__(self, x, y):
3        self.x = x
Tip
Always define __repr__. It costs two lines and makes every debugging session easier, because lists of your objects print readably.

Equality and Hashing

By default, == on two objects checks whether they're the same object, which is why two Point(3, 4) instances weren't equal. __eq__ defines what equality means for your class. __hash__ returns an integer for the object, and it's what lets instances go in a set or be used as dictionary keys. Objects that are equal must have the same hash, so the usual approach is to hash a tuple of the same fields __eq__ compares:

python
1class Point:
2    def __init__(self, x, y):
3        self.x = x
Warning
Defining __eq__ without __hash__ makes instances unhashable, so putting one in a set raises TypeError: unhashable type: 'Point'. Only make an object hashable if its fields won't change while it's in a set or dictionary; changing them would leave it stored under the wrong hash.

Ordering

__lt__ defines <, which is all sorted(), min() and max() need to order your objects:

python
1def __lt__(self, other):
2    return (self.x, self.y) < (other.x,

With that method added to Point, sorted([Point(2, 1), Point(1, 5)]) returns [Point(1, 5), Point(2, 1)]. The remaining comparison operators each have their own method (__le__, __gt__, __ge__); the functools.total_ordering decorator fills them in from __eq__ and __lt__.

Operators and Containers

Arithmetic operators have special methods too, such as __add__ for + and __sub__ for -. Adding them lets points add like vectors:

python
1def __add__(self, other):
2    return Point(self.x + other.x, self.y + other.y)

Point(1, 2) + Point(3, 4) then returns Point(4, 6).

A class that holds a collection can support len(), indexing and for loops with __len__, __getitem__ and __iter__:

python
1class Path:
2    def __init__(self, points):
3        self.points = 

Context Managers

The with statement, which you'll use for opening files, works with any object that defines __enter__ and __exit__. __enter__ runs at the start of the block, and its return value is what as binds. __exit__ runs when the block ends, even if an exception was raised inside it, which makes it the right place for cleanup:

python
1import time
2
3class Timer:
4    def __enter__(self):
5

__exit__ receives the exception's type, value and traceback if the block raised one, or three None values if it didn't. Returning True from it swallows the exception; returning anything else, including nothing, lets it continue.

Inheritance

A class can inherit from another, taking all of its attributes and methods and then adding or changing some. The class being inherited from is the parent (or base) class, and the new one is the child (or subclass):

python
1class Point3D(Point):
2    def __init__(self, x, y, z):
3

super() reaches the parent class, so super().__init__(x, y) lets Point set up x and y before Point3D adds z. A method defined in the child overrides the parent's method of the same name, as __repr__ does here. Methods the child doesn't define, such as __add__, are inherited as they are.

Every class ultimately inherits from object, which is where the default __repr__ and __eq__ come from. You'll write subclasses most often when a library asks for one, such as defining your own exception types.

Composition over inheritance
Inheritance says "a Point3D is a Point", and it's easy to overuse. Often a class works better by holding other objects as attributes, which is called composition: the Path class above has points rather than being one. Reach for inheritance when the child really is a more specific kind of the parent.

Dataclasses

Classes that mostly hold data, like Point, need a lot of repetitive code: an __init__ that copies every argument, a __repr__, and an __eq__. The @dataclass decorator from the dataclasses module writes all of these for you from a list of typed fields:

python
1from dataclasses import dataclass
2
3@dataclass
4class Point:
5    x: 

The type annotations are what tell @dataclass which fields exist, but as with all type hints, Python doesn't enforce them. Regular methods work exactly as before.

Options on the decorator generate more:

  • @dataclass(frozen=True) makes instances immutable, so assigning to a field raises an error, and makes them hashable. Frozen dataclasses are ideal as set members and dictionary keys, such as grid coordinates.
  • @dataclass(order=True) generates <, <=, > and >=, comparing fields in the order they're declared.

Fields can have defaults. A mutable default, such as a list, must use field(default_factory=list) so each instance gets its own; a plain = [] raises a ValueError for exactly the shared-list reason above:

python
1from dataclasses import dataclass, field
2
3@dataclass
4class Host:
5    address:

For a simple immutable record, typing.NamedTuple is a lighter alternative. It creates a tuple with named fields, so it also unpacks like one:

python
1from typing import NamedTuple
2
3class Point(NamedTuple):
4    x: int
5

For most data-holding classes you write from now on, start with @dataclass and only write the special methods by hand when you need something it doesn't generate.

self
.
y
=
y
4
b
.
x
# Return: 5
(
0
,
1
)
,
(
-
1
,
0
)
]
3
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8Point.DIRECTIONS[0] # Return: (0, -1)
9Point(0, 0).DIRECTIONS[0] # Return: (0, -1), instances see it too
x
4 self.y = y
5
6 def manhattan(self, other):
7 return abs(self.x - other.x) + abs(self.y - other.y)
8
9 def neighbors(self):
10 return [Point(self.x + dx, self.y + dy) for dx, dy in [(0, -1), (1, 0), (0, 1), (-1, 0)]]
11
12a = Point(1, 2)
13b = Point(4, 6)
14a.manhattan(b) # Return: 7
15len(a.neighbors()) # Return: 4
4
self
.
y
=
y
5
6 @classmethod
7 def from_string(cls, text):
8 x, y = text.split(",")
9 return cls(int(x), int(y))
10
11p = Point.from_string("3,4")
12p.x # Return: 3
self
.
y
=
y
5
6 @property
7 def length(self):
8 return (self.x ** 2 + self.y ** 2) ** 0.5
9
10Point(3, 4).length # Return: 5.0, no parentheses
4>>> Point(3, 4) == Point(3, 4)
5False
4
self
.
y
=
y
5
6 def __repr__(self):
7 return f"Point({self.x}, {self.y})"
8
9 def __str__(self):
10 return f"({self.x}, {self.y})"
11
12p = Point(3, 4)
13repr(p) # Return: 'Point(3, 4)'
14print(p) # Console: (3, 4)
4 self.y = y
5
6 def __eq__(self, other):
7 return (self.x, self.y) == (other.x, other.y)
8
9 def __hash__(self):
10 return hash((self.x, self.y))
11
12Point(3, 4) == Point(3, 4) # Return: True
13len({Point(3, 4), Point(3, 4), Point(0, 0)}) # Return: 2
other
.
y
)
list
(
points
)
4
5 def __len__(self):
6 return len(self.points)
7
8 def __getitem__(self, i):
9 return self.points[i]
10
11 def __iter__(self):
12 return iter(self.points)
13
14path = Path([Point(0, 0), Point(0, 1), Point(1, 1)])
15len(path) # Return: 3
16path[-1] # Return: Point(1, 1)
17[p.x for p in path] # Return: [0, 0, 1]
self
.
start
=
time
.
perf_counter
(
)
6 return self
7
8 def __exit__(self, exc_type, exc, tb):
9 self.elapsed = time.perf_counter() - self.start
10 print(f"took {self.elapsed:.3f}s")
11
12with Timer():
13 sum(range(10_000_000)) # Console: took 0.152s (your time will differ)
super
(
)
.
__init__
(
x
,
y
)
4 self.z = z
5
6 def __repr__(self):
7 return f"Point3D({self.x}, {self.y}, {self.z})"
8
9p = Point3D(1, 2, 3)
10p.x # Return: 1, set by Point.__init__
11p # Return: Point3D(1, 2, 3)
12isinstance(p, Point) # Return: True
int
6 y: int
7
8 def manhattan(self, other):
9 return abs(self.x - other.x) + abs(self.y - other.y)
10
11p = Point(3, 4)
12p # Return: Point(x=3, y=4)
13p == Point(3, 4) # Return: True
14p.manhattan(Point(0, 0)) # Return: 7
str
6 port: int = 22
7 open_ports: list = field(default_factory=list)
8
9Host("10.0.0.5") # Return: Host(address='10.0.0.5', port=22, open_ports=[])
y
:
int
6
7p = Point(3, 4)
8x, y = p # x = 3, y = 4
9p.x # Return: 3