[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

newb question about @property

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?

  class Celsius:
   def __init__(self, temperature = 0):
       self._temperature = temperature
   def temperature(self):
       print("Getting value")
       return self._temperature
   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.

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