Special methods

__str__, __repr__, __eq__ and comparing objects.

Methods with double underscores on both sides are called special. Python calls them on its own in certain situations. You already know __init__. Here are a few more:

  • __str__: what str(obj) returns and what print(obj) shows;
  • __repr__: how the object looks when debugging and inside lists;
  • __eq__: what a == b means;
  • __lt__: what a < b means, and then the objects can be sorted;
  • __len__: what len(obj) returns.

Without your own __str__, printing an object gives something like <__main__.Point object at 0x7f...>. With it you get clear text:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

print(Point(1, 2))   # (1, 2)

By convention __repr__ shows the object the way it can be created in code: Point(1, 2). If only __repr__ is defined, print uses it too.

By default == on objects checks whether it is the very same object, not whether the data are equal. Two different points with the same coordinates are not equal. To compare by content, define __eq__:

def __eq__(self, other):
    return self.x == other.x and self.y == other.y

Once you define __eq__, Python no longer considers the object hashable: it cannot go into a set or be a dictionary key until you also define __hash__. In the next lesson dataclass does all of this for you.

Practice

  1. Printing an object

    What does the program print?

    class P:
        def __str__(self):
            return "point"
    
    print(P())
    
  2. Equality by default

    What does == compare for objects of a class without its own eq?

    • Whether it is the very same object
    • All the attributes one by one
    • The names of the classes
    • The result of str(obj)
  3. Money

    Write a class Money with an amount attribute. str(Money(5)) should give 5.00 (two digits after the point), and two Money objects with the same amount should be equal with ==.