osdir.com


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

newb question about @property


Steve D'Aprano wrote:
> Circle didn't use any setters, but I could have let you set the 
> diameter, which in
> turn would set the radius:
>
> circle.radius = 2
> assert circle.diameter == 4
> circle.diameter == 2  # requires a setter
> assert circle.radius == 1
>
> Getting that to work is left as an exercise :-)
>
It WAS a good exercise!!  I was concerned about "infinite recursion" 
between my two property setters..  Thanks!   Next?  :)

Bill


import math


class Circle(object):
     """ Define a circle class with radius and diameter""" def __init__(self, radius):
         self.radius = radius
         self.diameter =2*radius

     @property def radius(self):
         return self._radius

     @radius.setter def radius(self, value):
         self._radius = value
         self._diameter=2*value

     @property def diameter(self):
         return self._diameter

     @diameter.setter def diameter(self, value):
         self._diameter = value
         self._radius = value /2 @property def area(self):
         return math.pi *self.radius **2 @property def circumference(self):
         return 2 * math.pi *self.radius

## Start here ## circle = Circle(1 / math.pi)
print("Area = {:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))

circle.radius =2 assert circle.diameter ==4 print("Area = {:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))

circle.diameter =2 # requires a setter assert circle.radius ==1 print("Area = {:.2f}".format(circle.area))
print("Circumference = {:.2f}".format(circle.circumference))