Class It Up: Doubt regarding scope of member variables


#1



https://www.codecademy.com/en/courses/python-intermediate-en-WL8e4/3/2?curriculum_id=4f89dab3d788890003000096#


The member variables angle1, angle2 and angle3 are defined in the method init(). Being defined in the method they shouldn't be accessible outside the method.


the 3 variables angle1, angle2, angle3 are accessible in the check_angles().
Also did not understand why check_angles() is being passed only self instead of self, angle1, angle2, angle3


lass 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, angle1, angle2, angle3):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False


#2

Checking the angles is done on the instance, self, which has those angles cached internally. It does not need those parameters.

They are defined on the instance which is scoped to the class.

my_triangle = Triangle(30, 60, 90)

print my_triangle.angle1    # 30
print my_triangle.angle2    # 60
print my_triangle.angle3    # 90

#3

@abhilav.sharma19,
Doing a google search
python method with only self parameter site:stackoverflow.com
finding
http://stackoverflow.com/questions/68282/why-do-you-need-explicitly-have-the-self-argument-into-a-python-method
in which
http://neopythonic.blogspot.nl/2008/10/why-explicit-self-has-to-stay.html


#4

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