This article brings together three tools that complete a class: special methods (with double underscores), attributes shared by all objects and composition.
Special methods
Names between double underscores (__init__, __str__…) are methods that Python calls automatically in specific situations:
| Method | When Python calls it | Example |
|---|---|---|
__init__ | When creating the object | Person("Ana") |
__str__ | With print(obj) or str(obj) | print(p) |
__repr__ | When showing the object in the console or inside a list | [p] |
__len__ | With len(obj) | len(album) |
__eq__ | With obj1 == obj2 | a == b |
__del__ | When the object is removed from memory | del p |
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def __str__(self):
return f"{self.owner}: {self.balance:.2f} €"
def __eq__(self, other):
return self.owner == other.owner and self.balance == other.balance
a1 = Account("Ana", 100)
a2 = Account("Ana", 100)
print(a1) # Ana: 100.00 €
print(a1 == a2) # True (without __eq__ it would be False)
Without __str__, print(a1) shows something like <__main__.Account object at 0x...>. With it, you decide the text. It is the idea of Person class and method ToString(): ToString() is the name it has in other languages.
The destructor: __del__
__del__ runs when Python frees the object from memory, that is, when no variable references it any more:
class Resource:
def __init__(self, name):
self.name = name
print(f"Opening {name}")
def __del__(self):
print(f"Closing {self.name}")
r = Resource("file") # Opening file
del r # Closing file
In Python it is almost never needed: memory is freed by itself. And it is not precisely known when it will be called in every case, so it is not a reliable place to close files or connections (that is what with is for). It appears in Constructors and destructors so you can see how it works.
Class attributes and instance attributes
An attribute defined with self in the constructor belongs to each object. One defined directly in the class is shared by all of them:
class Student:
total = 0 # class attribute
def __init__(self, name):
self.name = name # instance attribute
Student.total += 1
Student("Ana")
Student("Luis")
print(Student.total) # 2
They are useful for counters, constants (PI = 3.14159) or common values.
Composition: an object inside another
Inheritance expresses "is a"; composition expresses "has a". A library has books, a car has an engine, an album has photos:
class Book:
def __init__(self, title):
self.title = title
class Library:
def __init__(self):
self.books = [] # a list of Book objects
def add(self, book):
self.books.append(book)
def __len__(self):
return len(self.books)
lib = Library()
lib.add(Book("Dune"))
lib.add(Book("Emma"))
print(len(lib)) # 2
Rule of thumb: if you hesitate between inheritance and composition, ask yourself "is a?" or "has a?". When both sentences make sense, composition is usually better, because it is more flexible.