0

Why doesn't this code work?

class Triangle(object):
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    number_of_sides = 3
    def check_angles(self):
        sum_of_angles = angle1 + angle2 + angle3 # PLS LOOK AT THIS LINE
        if sum_of_angles == 180:
            return True
        else:
            return False

but this does?

class Triangle(object):
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    number_of_sides = 3
    def check_angles(self):
        sum_of_angles = self.angle1 + self.angle2 + self.angle3 # LOOK HERE AGAIN
        if sum_of_angles == 180:
            return True
        else:
            return False

if self.angle1 = angle1, why can't I just use the shorter version?

  • That is just how it is: `angle1` is a variable whose scope is the constructor, while `self.angle1` is a property of `self`. They are not the same thing. – trincot Dec 29 '16 at 12:03

1 Answers1

0

So to explain this, consider the following. When you get to the function Triangle.check_angles, consider what is defined at that point. You have your self object, which has angle1, angle2 and angle3 defined (i.e. you have self.angle1, self.angle2 and self.angle3 defined).

However, angle1 itself is not a known variable, as it is not passed into the function (like it is in the self.__init__ function). Thus if you ask for angle1, it is not defined, and raises an error. Is that clear?

Right leg
  • 16,080
  • 7
  • 48
  • 81
A. N. Other
  • 392
  • 4
  • 14