Sub topic 1
How Python Maps Syntax to Special Methods
Prerequisites
This chapter assumes you can define classes, create instances, use instance attributes, and work with lists, tuples, and for loops.
The data model
Python syntax often calls a special method, also called a dunder method because its name has double underscores. For example, len(item) calls type(item).__len__(item), and a == b calls an equality method on the objects' types.
Making objects printable
Implement __repr__ for a useful debugging representation. It should identify the object and, when practical, show how it was built. Implement __str__ for a friendlier message shown by print().
If __str__ is missing, str(obj) falls back to __repr__. Keep representations short and unambiguous.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def __repr__(self):
return f"Version({self.major}, {self.minor})"
def __str__(self):
return f"{self.major}.{self.minor}"
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) < (other.major, other.minor)
def __hash__(self):
return hash((self.major, self.minor))
versions = {Version(1, 2), Version(1, 2)}
print(versions) # {Version(1, 2)}
print(str(Version(1, 2))) # 1.2
print(Version(1, 2) <= Version(2, 0)) # TrueCreating objects
__new__ creates and returns an instance. Python then calls __init__ to initialize that instance. Most classes need only __init__. Override __new__ when controlling instance creation, such as for immutable types or caching.
Equality and ordering
__eq__ defines equality. A class is hashable when it supplies a stable __hash__, allowing instances in sets and as dictionary keys. Equal objects must have equal hashes. Do not hash objects using fields that can change after insertion.
__lt__ defines “less than.” The @total_ordering decorator from functools derives the other ordering methods from __eq__ and one ordering method. It is convenient, though explicit methods can be faster.
Exercise
Why must equal objects return the same hash value?
Show answer
Sets and dictionaries use the hash to locate entries, then use equality to confirm a match.