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.
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:
1class Point:
2 def __init__(self, x, y):
3 self.x = x
4Calling the class like a function creates a new object, called an instance, and passes the arguments to __init__:
1p = Point(3, 4)
2p.x # Return: 3
3p.y # Return: 4The 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:
1a = Point(1, 2)
2b = Point(5, 6)
3a.x # Return: 1
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:
1class Point:
2 DIRECTIONS = [(0, -1), (1, 0),__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.A method is a function defined inside a class. Methods take self first and use it to reach the instance's attributes:
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.
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:
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.
The @property decorator turns a method into something that reads like an attribute. It's useful for values computed from other attributes:
1class Point:
2 def __init__(self, x, y):
3 self.x = x
4Python 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.
So far, printing a Point or comparing two of them gives unhelpful results:
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__().
__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__:
1class Point:
2 def __init__(self, x, y):
3 self.x = x
__repr__. It costs two lines and makes every debugging session easier, because lists of your objects print readably.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:
1class Point:
2 def __init__(self, x, y):
3 self.x = x
__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.__lt__ defines <, which is all sorted(), min() and max() need to order your objects:
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__.
Arithmetic operators have special methods too, such as __add__ for + and __sub__ for -. Adding them lets points add like vectors:
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__:
1class Path:
2 def __init__(self, points):
3 self.points = 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:
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.
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):
1class Point3D(Point):
2 def __init__(self, x, y, z):
3super() 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.
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.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:
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:
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:
1from typing import NamedTuple
2
3class Point(NamedTuple):
4 x: int
5For 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.