[Tutor] Concept related to python classes
Manprit Singh
manpritsinghece at gmail.com
Mon Sep 7 01:17:13 EDT 2020
Dear Sir ,
Consider a problem to find the area of a triangle , using classes .
self.a, self.b, self.c are instance variables representing 3 arms of
triangle.
I need an instance variable self.area that represents the area of the
triangle.
class Area:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
self.calculate()
def calculate(self):
s = (self.a + self.b + self.c) / 2
self.area = (s * (s - self.a) * (s - self.b) * (s - self.c))**0.5
tri = Area(4, 4, 3) # Object initialization
print(tri.area) #Will print 5.562148865321747 (area when arms are
4,4,3)
tri.a = 3
tri.b = 4
tri.c = 5
tri.calculate() # Method called To calculate the area with arms
(3,4,5)
print(tri.area) # will print 6.0
My first question is -
The way I have used self.area as instance variable inside class definition
.
The point is i haven't written self.area inside the __init__( ) .
Is it not necessary to place an instance variable inside __init__( ) ?
My second question is :
The way i have called self.calculate() inside the __init__( ) is ok ?
My idea behind this is, upon calling this function inside __init__( ), the
area
triangle for initial values of the arms will be calculated and the
calculated
value of the area will be assigned to instance variable self.area.
Is this idea correct thinking ?
My third question is :
As you can can see i have reassigned the values of length of arms as :
tri.a = 3
tri.b = 4
tri.c = 5
and after it tri.calculate() is called , and then tri.area gives the
desired output.
Just need to know if this is the efficient approach to calculate the result
for the
re assigned values of arms measurements after the initialized values of
arms measurement.
I have not used getters & setters as python do not promote use of getters
and setters unless otherwise these are necessarily required.
Regrads
Manprit Singh
More information about the Tutor
mailing list