Helio Junior
Helio Junior

Reputation: 163

About use of underscore, or not, at the same class attribute in Python

Why in this example, sometimes the author use self._temperature and self.temperature (with and without underscores) for the same attribute ?

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

Upvotes: 0

Views: 243

Answers (1)

chepner
chepner

Reputation: 531808

There are two separate attributes in use here. _temperature is an instance attribute, while temperature is a class attribute, whose value is a property object. Accessing temperature triggers a method call which acts upon the instance variable _temperature.

The use of the underscore indicates something is "private", and should not be accessed directly. It is a common convention for the name of the attribute backing a property to be the name of the property prefixed with a _.

Upvotes: 3

Related Questions