[Tutor] Concept related to python classes

boB Stepp robertvstepp at gmail.com
Mon Sep 7 16:26:11 EDT 2020


On Mon, Sep 07, 2020 at 07:22:40AM -0600, Mats Wichmann wrote:
>On 9/7/20 3:59 AM, Manprit Singh wrote:

>> 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
>
>    @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

>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?

Mats, you have me wondering where you are going with this, so I will be the
first one to (perhaps) make the foolish mistake.  I want to learn, too!  I hope the OP
is giving this some thought as you intended!

The most natural thing to me is to use either the __init__ method or the
resize method to solely set the size of the triangle.  But if the former is used
then a new object will be created, which from context I guess would be
undesirable.  So I would probably make these modifications:

def __init__(self, a, b, c):
     self.set_size(a, b, c)

def set_size(self, a, b, c):  # "resize" seems an inappropriate name now
     self.a = a
     self.b = b
     self.c = c

It would appear to function correctly:

3.8.3:  t = Triangle(3, 4, 5)
3.8.3:  t.a
3
3.8.3:  t.b
4
3.8.3:  t.c
5
3.8.3:  t.set_size(9, 10, 11)
3.8.3:  t.a
9
3.8.3:  t.b
10
3.8.3:  t.c
11

If one wanted to do input validation, one could individually make a, b, c
properties with setter methods that do the validation.

This is what *I* am thinking.  What are you thinking here?

If I am on the right track is calling a method from _init__() to
massage/validate data a common thing to do in OOP?

-- 
Wishing you only the best,

boB Stepp


More information about the Tutor mailing list