16 - Class It Up - I got it right but don't know why



Just wondering, with my code, in the check_angles method, I only use self as an argument, why dont i use angle1, angle2 and angle3 as arguments too?

class Triangle:
    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
            return False


The __init__ method let's you construct a new object of a class. It needs the angle1, angle2 and angle3 paramters to initialize the new object.

The check_angles can be used after some object of the Triangle type was created.

When you use __init__ the object is not created yet, and thus doesn't have values for the self.angle1 etc. attributes yet.
When you use check_angles the object already has these attributes and you can access them from inside the method.

Edit: This is incorrect, see @ionatan's reply.


Triangle objects have those attributes, so if you have a reference to a Triangle object then you have access to those attributes as well.

The object does exist when __init__ is called! The name self refers to it. __init__ can then do any operations that need to happen to the object before the object is used outside the class, such as adding attributes that are specific to that object.


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