Need help with Python Classes


#1

I need help with init() , like what does it actually do? And also consider the code:

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
class Equilateral(Triangle):
  angle=60
  def __init__(self):
    self.angle1=self.angle
    self.angle2=self.angle
    self.angle3=self.angle
    
my_triangle=Triangle(90,30,60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

In the derived class, why do I have to use self.angle to access the angle variable when it is already in the class?
And I need a clear explanation of what “self” is and how it works.
As a person who came from C++, I feel really comfortable with the C++ style of classes, objects, overriding (and using virtual functions) and Inheritance. But this new Python style of things really confuse me.


#2

self refers to the current instance of the class, which you can see really nicely if you do:

my_triangle=Triangle(90,30,60)
print Triangle.check_angles(my_triangle)

Given i call the method on the class, i have to pass the instance as argument (for self parameter).

class variable (like angle in Equilateral class) are automatically added to self by python, and is shared between the instances


#3

So I should still use theself while referring to angle inside the class?


#4

yes, to access class variable, instance variable and methods inside a method all require self