newb question about @property

Cameron Simpson cs at cskk.id.au
Sat Sep 30 21:43:11 EDT 2017


On 30Sep2017 20:07, Bill <BILL_NOSPAM at whoknows.net> wrote:
>think all of this would have made a bit more sense (to me), if instead of just 
>"@property", the syntax was "@property.getter".

Perhaps, but nobody wants to type this. Also many properties are ready only, so 
that is the default.

>Now I am forced to ask the question, why did they use the underscore (on 
>temperature) in the example on the bottom of this page? Is one forced to 
>introduce new identifiers in order to define a setter?
>https://www.programiz.com/python-programming/property

  class Celsius:
   def __init__(self, temperature = 0):
       self._temperature = temperature
   [...snip...]
   @property
   def temperature(self):
       print("Getting value")
       return self._temperature
   @temperature.setter
   def temperature(self, value):
       if value < -273:
           raise ValueError("Temperat
       print("Setting value")
       self._temperature = value

because the name self.temperature is taken by the property, one must store 
underlying values in a different name. Since the property is one to one with 
the actual internal value here and they're just using the setter protery to do 
a sanity check, they named the internal value very similarly. By using 
"_temperature" they (a) keep the name very similar and (b) make it clear that 
the internal value is "private", not intended for direct use by code outside 
the class.

Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)



More information about the Python-list mailing list