Introduction to Classes - 18. Inheritance - cannot instantiate?


#1

Hello!

My code for this lesson is

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
  def sum_angles(self):
    return (self.angle1 + self.angle2 + self.angle3)
  
my_triangle = Triangle(90, 30, 60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
  angle = 60
  def __init__(self):
    self.angle1 = self.angle
    self.angle2 = self.angle
    self.angle3 = self.angle

Which so far seems to work fine. But when I try to pass an instance of Equilateral to test how this works, like so

my_triangle2 = Equilateral(60,60,60)
print my_triangle2.number_of_sides
print my_triangle2.check_angles()

I get the following message on the console:

3
True
180
Traceback (most recent call last):
  File "python", line 28, in <module>
TypeError: __init__() takes exactly 1 argument (4 given)

I understand this comes from trying to pass (60, 60, 60) on the __init__(self) function of Equilateral, but I thought it would need the same number of arguments as its parent class Triangle. Isn´t this the case?

Just to be sure, if I call my_triangle2 = Equilateral(60) I get the same error, but with a takes exactly 1 argument (2 given) variation.

And if I try to pass the instance with no arguments declared, as in

my_triangle2 = Equilateral
print my_triangle2.number_of_sides
print my_triangle2.check_angles()

then the error message becomes

Traceback (most recent call last):
  File "python", line 30, in <module>
TypeError: unbound method check_angles() must be called with Equilateral instance as first argument (got nothing instead)

Sorry for the very long message, but I am beyond confused :s

Thanks in advance for any help you can provide!


#2

If you look at the __init__ method, you will see there is but one parameter, self. Instantiate with no arguments…

my_triangle2 = Equilateral()

#3

Of course! I should have seen it straight away… :man_facepalming:

Sorry for the silly question, and thanks a lot for the answer! :smile:


#4

You override __init__, you only keep what you don’t redefine

And, here, you don’t instantiate the class at all, because you don’t call the type/class

Anyway, don’t pay too much attention to inheritance, it’s not all that useful in python where it’s mostly used to provide default behaviour for undefined things, it rarely matters what something is, only how it behaves.


#5

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