0

I have a question on (which could be said to be an extension on another question but I couldnt comment yet) python - attribute x is a property object which provides interface to this private variable

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

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

    def get_temperature(self):
        print("Getting value")
        return self._temperature

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

    temperature = property(get_temperature, set_temperature)

So initially I was having problems with "maximum recurson"/ stack overflow error in which cause by the temperature keep calling the setter which then calls itself.

The solution seems to be by convention adding underscore infront => "_temperature" or any other name which makes it becomes a private variable so it stops calling itself

My question still remains after searching for all questions related is that how does the function knows to store the value of "temperature" to "_temperature" unless it is really obvious but I could not figure it out.

Thank you for helping out, new Python learner, started in Java so the private and public concept kinda conflicts with over here.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
Intern
  • 39
  • 1
  • 5
  • 2
    For a `property` named `temperature`, `self.temperature = ...` invokes the setter method, in this case `set_temperature`. Here the assignment `self._temperature = ...` is made which is a different name because of the underscore (hence no setter is invoked). It's an explicit assignment. – a_guest Mar 14 '20 at 08:01
  • Does this answer your question? [How does the @property decorator work?](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work) – kaya3 Mar 14 '20 at 09:55
  • Thank you so much @a_guest, I somehow didnt see the `self._temperature = value` which explicitly assigns values to `self._temperature` which also prevents recursions from happening – Intern Mar 15 '20 at 03:26
  • @kaya3 yes I did saw that, it just I somehow didnt see the part where they explicitly assign value to _variable. Thank you guys – Intern Mar 15 '20 at 03:27
  • @a_guest if you have time could you copy paste your comment to an answer so I could acccept it – Intern Mar 15 '20 at 03:31
  • If your question asking for an explanation of the code was caused by you missing the relevant part of the code when you read it, and that part is explained in another Q&A - then the question ought to be closed, not answered, since the issue was resolved in a way that is unlikely to be useful to others. – kaya3 Mar 15 '20 at 10:46

0 Answers0