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

newb question about @property

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?



> This is a particularly simple example, with only getters. How would you write it
> by overriding __get__?
> class Circle(object):
>      def __init__(self, centre, radius):
>          self.centre = centre
>          self.radius = radius
>      @property
>      def diameter(self):
>          return 2*self.radius
>      @property
>      def area(self):
>          return pi*self.radius**2
>      @property
>      def circumference(self):
>          return pi*self.diameter