How do I add a member variable to the Triangle class?

Question

How do I add a member variable to the Triangle class?

Answer

Recall that a member variable is one that’s inside of a class and available to all methods within that class, meaning it’s outside of the methods but inside of the class. So be sure to indent the member variable to 2 spaces so it’s inside the class, like this:

class MyClass(object):
  my_member_var = 10  # My member variable!

  def __init__(self):
    pass
2 Likes

I just have a simple doubt in this exercise: given it is an advanced class, why wouldn’t it be allowed in the answer to be using the funtion sum to add up the sides of the triangle instead of arg1 + arg2+arg3?

Thanks

Are we to assume,

class Triangle:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def perimeter(self):
        return self.a + self.b + self.c

print (Triangle(3, 4, 5).perimeter())    # 12

Why do you not need to list angle1, angle2, and angle3 as parameters in the check_angles definition?

3 Likes

The check_angles method is only called after the instance of Triangle from which it is called has already been created. During that instantiation process, the three angles are specified as arguments. Thereafter, any method of Triangle has access to the values that pertain to that instance. Accordingly, the values do not need to be specified again when methods are called from that instance.

2 Likes

why does only self.angle1…ect work
why cant i just pass angle1 into def check_angles?

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):

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

  return True

else:

  return False

triangle = Triangle(10,10,10)

print triangle.check_angles()

1 Like

We don’t have to pass anything into that method since it acts directly upon the instance, itself. The values are internal to self, hence, self.angle1, &c.

triangle = Triangle(10,10,10)

print triangle.check_angles()

Surely you are expecting False since the angles of a triangle must add up to 180, no exceptions.

1 Like

Hello all.

Currently going through this python 2.7 course and the forum topics on this course were very helpful.

Regarding this topic. I have a different question. What is the point of creating a member variable in the first place since we don’t even use it in this exercise? Is it just to exercise our knowledge?