[Tutor] Concept related to python classes

Mats Wichmann mats at wichmann.us
Mon Sep 7 09:22:40 EDT 2020


On 9/7/20 3:59 AM, Manprit Singh wrote:
> Dear Sir,
> 
> This is a continuation mail.
> I have just tried to  rewrite the program of finding the area of a
> triangle, as per the explanation given in the previous mail.
> 
> 
> class Triangle:
>     def __init__(self, a, b, c):
>         self.a = a
>         self.b = b
>         self.c = c
> 
>     def area(self):
>         s = (self.a + self.b + self.c) / 2
>         return (s * (s - self.a) * (s - self.b) * (s - self.c))**0.5

This one is just down to style: Alan mentioned avoiding keeping more
instance variables than you need, and in fact - derive the ones you can
derive, so things stay better in sync.  That said, you can make "area"
look like an instance variable (or attribute, or property - the terms
can overlap a little bit here), and still have it be calculated upon need:

    @property
    def area(self):
        s = (self.a + self.b + self.c) / 2
        return (s * (s - self.a) * (s - self.b) * (s - self.c))**0.5

>     def resize(self, a1, b1, c1):
>         self.a = a1
>         self.b = b1
>         self.c = c1
> 
> 
> tri = Triangle(4, 4, 3)

Now the access to this is able to be:

> print(tri.area())            # Gives the answer =  5.562148865321747

print(tri.area)

which to me feels a more natural way to express "what is the area of
tri" - . Notice the implementation itself didn't change at all.

> tri.resize(3, 4, 5)         # This allows you to change all arms of
> triangle in one line
> print(tri.area())            # # Gives the answer =  6.0
> 
> Regards
> Manprit Singh

Now, a challenge question: the contents of the __init__ method are
identical to the contents of the resize method (excepting yout choice of
parameter names).  Many of the more clever IDE packages will actually
warn you about duplicated code like this.  Can you think of a natural
way to address that?


More information about the Tutor mailing list