Implement the Python dunder methods that make a class printable, comparable and usable with len().
Dunder methods have double underscores on both sides of the name. They are the hooks that the interpreter calls for built-in operations. You never call them yourself, because the ordinary syntax calls them for you.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __repr__(self):
return 'Temperature(' + str(self.celsius) + ')'
def __str__(self):
return str(self.celsius) + ' C'
def __len__(self):
return 3
def __eq__(self, other):
if not isinstance(other, Temperature):
return False
return self.celsius == other.celsius
reading = Temperature(20)
print(reading) # 20 C
print(repr(reading)) # Temperature(20)
print(len(reading)) # 3
print(reading == Temperature(20)) # True
Printing an object calls __str__, and when a class does not define __str__ Python falls back to __repr__. Calling repr() directly calls the other method, and that one is aimed at developers. A good __repr__ returns text that would rebuild the object if you pasted it into Python.
len() calls __len__, and the == operator calls __eq__. Defining __eq__ is enough to make the == comparison work. Notice that the example checks the type of the other value first, so the comparison returns False instead of raising an error when the two values are of different types.
One consequence is worth knowing. Defining __eq__ sets __hash__ to None unless you define it yourself, and that makes the objects unhashable and therefore useless as dictionary keys. If you want equality and hashability, you must write both, and they must agree, because two objects that compare equal have to have the same hash.