Implement the Python dunder methods that make a class printable, comparable and usable with len().
Dunder methods — double underscore on both sides — are the hooks the interpreter calls for built-in operations. You do not call them directly; the syntax calls them for you.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __repr__(self):
return f"Temperature({self.celsius})"
def __str__(self):
return f"{self.celsius} C"
def __len__(self):
return 3
def __eq__(self, other):
return isinstance(other, Temperature) and self.celsius == other.celsius
t = Temperature(20)
print(t) # 20 C
print(repr(t)) # Temperature(20)
print(len(t)) # 3
print(t == Temperature(20)) # TruePrinting the object calls str, which falls back to repr when __str__ is not defined. Calling repr on it directly calls the other method, which is the one aimed at developers — the representation should ideally be valid Python source that recreates the object.
len() calls __len__, and the == operator calls __eq__. Notice that defining __eq__ is enough to make the == comparison work, and that the implementation checks the type of the other operand first so the comparison returns False rather than raising when the types differ.
One consequence worth knowing. Defining __eq__ sets __hash__ to None unless you define it explicitly, which makes instances unhashable and therefore unusable as dictionary keys. If you want equality and hashability, you must write both — and they must agree, since two objects that compare equal must hash the same.