[Edu-sig] a Circle type with radius, area both properties

Wes Turner wes.turner at gmail.com
Wed Oct 19 14:40:17 EDT 2016


https://en.wikipedia.org/wiki/Observer_pattern

- https://docs.python.org/2/reference/datamodel.html#object.__setattr__
-
https://github.com/ipython/traitlets/#callbacks-when-a-trait-attribute-change
  - https://traitlets.readthedocs.io/en/stable/using_traitlets.html#observe
@observe decorator

https://en.wikipedia.org/wiki/Reactive_programming


On Wednesday, October 19, 2016, kirby urner <kirby.urner at gmail.com> wrote:

>
> Speaking of sharing Python with math teachers, not just
> librarians (the bravest I sometimes thing), I included this
> Circle in the session last night (adults learning, andragogy
> at work):
>
> class Circle:
>     """setting either the radius or area attribute sets the other       as a dependent value.  Initialized with radius only, unit        circle by default.    """
>
>     def __init__(self, radius = 1):
>         self.radius = radius
>
>     @property
>     def area(self):
>         return self._area
>
>     @property
>     def radius(self):
>         return self._radius
>
>     @area.setter
>     def area(self, value):
>         self._area = value
>         self._radius = self.area / (2 * math.pi)
>
>     @radius.setter
>     def radius(self, value):
>         self._radius = value
>         self._area = math.pi * (self.radius ** 2)
>
>     def __repr__(self):
>         return "Circle(radius = {})".format(self.radius)
>     the_circle = Circle(5)print("the_circle:", the_circle)print("Area: ", the_circle.area)the_circle.area = 50print("Radius when Area=50:", the_circle.radius)
>
> That's right, the area changes if you set the radius
> attribute and the other way around.  I'm not claiming
> to be the first to think of doing this.
>
> We're free to program a lot of geometric types like
> that, that keep track of their own area and volume (a
> theme at thekirbster.pythonanywhere.com as well,
> the tiny Flask application I use as a classroom demo).
>
> Here's the Jupyter Notebook I put together before
> class, where the above Circle type appears:
>
> https://github.com/4dsolutions/Python5/blob/master/Descriptors%20and%
> 20Properties.ipynb
>
> (also viewable in nbviewer.jupyter.org, just paste
> in the URL).
>
> Kirby
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20161019/7f1bcf72/attachment-0001.html>


More information about the Edu-sig mailing list