Calling a parent class constructor from a child class in python

PythonInheritance

Python Problem Overview


So if I have a class:

 class Person(object):
'''A class with several methods that revolve around a person's Name and Age.'''

    def __init__(self, name = 'Jane Doe', year = 2012):
        '''The default constructor for the Person class.'''
        self.n = name
        self.y = year

And then this subclass:

 class Instructor(Person):
'''A subclass of the Person class, overloads the constructor with a new parameter.'''
     def __init__(self, name, year, degree):
         Person.__init__(self, name, year)

I'm a bit lost on how to get the subclass to call and use the parent class constructor for name and year, while adding the new parameter degree in the subclass.

Python Solutions


Solution 1 - Python

Python recommends using super().

Python 2:

super(Instructor, self).__init__(name, year)

Python 3:

super().__init__(name, year)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel Love JrView Question on Stackoverflow
Solution 1 - PythonvinnydiehlView Answer on Stackoverflow