single leading undescore means this is "for internal use only" variable.
This is defined in PEP8:
In your example you want to raise error when values is < -273.15. So, every time you do
Later when you try to access
As I said, it's just a convention and one has access to
This is defined in PEP8:
Quote:_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose names start with an underscore.Still, this is only convention - user has access to it, but the intention of the programmer is clear.
In your example you want to raise error when values is < -273.15. So, every time you do
self.temperature
the setter is called (the function decorated as @temperature.setter
). Now you need to store the value somewhere (if it pass the test) and you use self._temperature
. Later when you try to access
self.temperature
, it will call the function decorated as @temperature.property
and it will return self._temperature
.As I said, it's just a convention and one has access to
_temprature
, but really should not work directly with it# Using @property decorator 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): print("Setting value...") if value < -273.15: raise ValueError("Temperature below -273 is not possible") self._temperature = value celsius = Celsius(100) print(celsius.temperature) celsius._temperature = -1000 print(celsius.temperature) celsius.temperature = -300
Output:Setting value...
Getting value...
100
Getting value...
-1000
Setting value...
Traceback (most recent call last):
File "/home/boyan/sandbox2/forum.py", line 25, in <module>
celsius.temperature = -300
File "/home/boyan/sandbox2/forum.py", line 18, in temperature
raise ValueError("Temperature below -273 is not possible")
ValueError: Temperature below -273 is not possible
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs