Jun-08-2020, 05:37 PM
The underscore differentiates the field from the methods. Without the underscore, Celsius.temperature will always call one of the methods instead of the variable and it ends up in an infinite recursion loop. The Celsius.temperature() methods would just keep calling themselves ad infinitum.
To walk through this particular example, Celsius:
To walk through this particular example, Celsius:
- Celsius.__init__(5) sets self.temperature to 5 by calling the Celsius.temperature() setter.
- Celsius.temperature() creates the self._temperature field and sets it to 5.
- Celsius.to_fahrenheit() calls the Celsius.temperature() getter.
- Celsius.temperature() returns the value of self._temperature.
- Celsius.to_fahrenheit() uses the result of Celsius.temperature() to calculate the Fahrenheit value and returns it.