Mina’s gallery display now converts readings through valueOf() and toString(). The conversion hint determines which method runs first. If that method returns an object, JavaScript tries the other. Mina’s Reading class has no say in that order.
That’s a problem for the display, which has to keep the label and the number apart. Mina wants one method in Reading that sees what each conversion asks for and returns the appropriate result: the label when the display asks for text, the Celsius value when it asks for a number. With two methods, JavaScript decides which answer a conversion gets by controlling their order.
JavaScript lets a class take over that decision with a single method. In this lesson, you’ll find out where that method lives, how to name it in a class, and what it has to return. You’ll answer the text request here and leave the other requests to the next lesson.
Look Up the Hook by Symbol
In Python, the display’s Reading class tells each conversion what to do through a method with a special name. Here’s the Python version:
class Reading:
def __init__(self, celsius):
self.celsius = celsius
def __str__(self):
return f"{self.celsius} C"
def __float__(self):
return float(self.celsius)
reading = Reading(21)
print(f"Reading: {reading}")
The f-string formats reading, falling back to __str__ by default, and the script prints Reading: 21 C. Python picks a method per conversion: __str__ for text, __float__ for float(). It finds them by name, since those names are ordinary strings and the double underscores are a naming convention.
JavaScript has a single hook that takes over ToPrimitive, the step behind an object’s conversions to strings and numbers. Boolean conversion doesn’t take part and never calls it.