Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

super() and the Inheritance Hierarchy

Give Feedback

In the previous lesson, you covered objects and inheritance. In this lesson, you’ll dive deeper into method overriding and see how to use super() to access overridden parent methods:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * self.length + 2 * self.width

    def what_am_i(self):
        return 'Rectangle'

class Square(Rectangle):
    def __init__(self, length):
        super().__init__(length, length)

    def what_am_i(self):
        return 'Square'

class Cube(Square):
    def surface_area(self):
        face_area = self.area()
        return face_area * 6

    def volume(self):
        face_area = super().area()
        return face_area * self.length

    def what_am_i(self):
        return 'Cube'

    def family_tree(self):
        return self.what_am_i() + ' child of ' + super(Cube, self).what_am_i() 

Comments & Discussion

Brandon on Jan. 29, 2020

Thanks for video. One problem, though. I keep getting an AttributeError when calling cube.volume(): type object ‘super’ has no attribute ‘area’ The cube instance of Cube has the property “area”, but it’s throwing an error when it goes looking for it in the parent(s). When I replace face_area = super().area() with face_area = self.area(), cube.volume() works fine. Any thoughts?

Brandon on Jan. 29, 2020

It appears the issue may be with the import into the iPython terminal. When I run the code in the Python Interactive Window in VS Code it’s fine, but calling cube.volume() after importing via the terminal (into iPython) throws the error. Oh well, no worries. Thanks!

Become a Member to join the conversation.