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

newb question about @property

On 2017-10-01 01:07, Bill wrote:
> Steve D'Aprano wrote:
>> On Sun, 1 Oct 2017 08:47 am, Bill wrote:
>>> I spent a few hours experimenting with @property. To my mind it seems
>>> like it would be preferable to just define (override) instance methods
>>> __get__(), __set__(), and possibly __del__(), as desired, as I could
>>> easily provide them with "ideal" customization. Am I overlooking something?
>> Probably.
> You and Ned are both right.  Up until a few minutes ago, I wasn't
> thinking about a class having more than 1 attribute that I wanted to
> change.  And now I realize that __get__ doesn't really make sense in
> that context (in the back of my mind was the notion that @property
> defined __get__, __set__ and __del__) and I allowed that to obscure my
> vision.   I was on the verge of giving up anything to do with computers,
> forever.  : )
> BTW, your example (below) is very nice!  I may have seen something
> similar before, but I am starting to appreciate it better now.  I think
> all of this would have made a bit more sense (to me), if instead of just
> "@property", the syntax was "@property.getter".  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
self._temperature is where the value is actually stored.

Suppose you had this instead:

     def temperature(self, value):
         if value < -273:
             raise ValueError("Temperature below -273 is not possible")
         print("Setting value")
         self.temperature = value # <-- changed this line

What would happen when you tried to set the temperature?

Because of the last line, the setter would be calling itself recursively 
until it hit the maximum stack depth.

A leading underscore is the normal convention to indicate that it should 
be treated as "private".

If you wanted the temperature to be read-only, you'd make the value 
"private" and have a getter but not a setter.