Class it up (Please clarify)


#1

class Triangle(object):
number_of_sides = 3
def init(self,angle1,angle2,angle3):
self.angle1 = angle1
self.angle2 = angle2
self.angle3 = angle3
def check_angles(self):
if self.angle1 + self.angle2 + self.angle3 == 180:
return True
else:
return False

Why must we write

((((if self.angle1 + self.angle2 + self.angle3 == 180))))

when we already assigned self.angle1 to angle1

should it not be if angle1 + angle2 + angle3 == 180

?


#2

The method's chief role is in proving that the angles inputed indeed add up correctly to 180 degrees.

When instantiating, it is possible to input any values as the three angles. The check_angles method is our tool for keeping things honest.

Note that there is no assignment taking place, only addition and comparison of the total.


#3

Thanks for the reply!

What I mean is why must we input the self. <--- in self.angle1

when we made
self.angle1
equal to
angle1
previously in our code

shouldn't our program already know that angle1 is self.angle1

why must we regress and input angle1 as self.angle1


#4

self is the variable that keeps track of the context object, the current instance. When an instance invokes a method, it points this variable to itself so it accesses the correct values in store.

my_triangle = Triangle(70, 60, 50)

print my_triangle.angle1    # 70

In the above statement, the context is my_triangle. When referred to by an instance method, it is self.

An __init__ method needs to include self in the parameter list so it is scoped to the code block and can append the instance assignments.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.