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__: whatstr(obj)returns and whatprint(obj)shows;__repr__: how the object looks when debugging and inside lists;__eq__: whata == bmeans;__lt__: whata < bmeans, and then the objects can be sorted;__len__: whatlen(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
Printing an object
What does the program print?
class P: def __str__(self): return "point" print(P())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)
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 ==.