Class It Up - Why (self)


#1

So in this example, I understand everything until I have to create my own method to check the angles.

Why is that I call self? Is that because self is an “instance” of the Triangle class?



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



#2

i think this stackoverflow question answers it nicely:

lets say we have two instances, triangle_one and triangle_two. If we now call check_angles method on triangle_one:

triangle_one = Triangle(60,60,60)
triangle_one.check_angles()

how does python know on which instance its calling the method? That is why we have self. This name could be anything, but self is a very convenient name


#3

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