[Tutor] Concept related to python classes

Richard Damon Richard at Damon-Family.org
Mon Sep 7 16:48:30 EDT 2020


On 9/7/20 12:15 PM, Manprit Singh wrote:
> Dear Sir,
> This is again a continuation mail . I have tried to solve the same problem
> of finding area of a triangle using decorators . and it seems more
> effective in comparison to my previous code, which is given below :
>
> class Triangle:
>     def __init__(self):
>         self._a = None
>         self._b = None
>         self._c = None
>         self._area = None
>
>     @property
>     def a(self):
>         """I'm the 'a' property."""
>         return self._a
>
>     @a.setter
>     def a(self, a1):
>         self._a = a1
>
>     @property
>     def b(self):
>         """I'm the 'b' property."""
>         return self._b
>
>     @b.setter
>     def b(self, b1):
>         self._b = b1
>
>     @property
>     def c(self):
>         """I'm the 'c' property."""
>         return self._c
>
>     @c.setter
>     def c(self, c1):
>         self._c = c1
>
>
>     def calcarea(self):
>         s = (self._a + self._b + self._c) / 2
>         self._area =  (s * (s - self._a) * (s - self._b) * (s -
> self._c))**0.5
>
>     @property
>     def area(self):
>         self.calcarea()
>         return self._area
>
>
>
> tri = Triangle()
> tri.a = 3
> tri.b = 4
> tri.c = 5
> print("Area of triangle with
> sides",tri.a,"&",tri.b,"&",tri.c,"is",tri.area)
> tri.a = 4
> tri.b = 4
> tri.c = 3
> print("Area of triangle with
> sides",tri.a,"&",tri.b,"&",tri.c,"is",tri.area)
>
> Output is as follows:
>
> Area of triangle with sides 3 & 4 & 5 is 6.0
> Area of triangle with sides 4 & 4 & 3 is 5.562148865321747
>
> Just see, after making the object of the class Triangle and assigning it to
> a variable tri , i am just going in an easy way similar to assigning values
> to the instance variables, although here in this example , by writing
> tri.a, tri.b & tri.c for setting, the setter function  for a particular
> instance variable is accessed due to property.
> and immediately after it , writing tri.area gives the area This seems more
> pythonic.
>
> What about adopting this practise ?
>
> Regards
> Manprit Singh

Personally, I wouldn't create the a, b, c as properties until I needed
them, since the property definitions just do exactly what a direct
access would.

For me:

class Triangle:

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

        self.a = a

        self.b = b

        self.c = c

    @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


Look Clearer?

There is also the suggestion I have heard that a class with two methods,
one being __init__, and one computing a result is often better as just a
function (unless you need the object as a scratch pad for some reason)

-- 
Richard Damon



More information about the Tutor mailing list