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
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
https://mail.python.org/mailman/listinfo/edu-sig

Reply via email to