61

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.

Sentient07
  • 1,270
  • 1
  • 16
  • 24
Daniel Love Jr
  • 950
  • 5
  • 13
  • 17

1 Answers1

115

Python recommends using super().

Python 2:

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

Python 3:

super().__init__(name, year)
vinnydiehl
  • 1,654
  • 1
  • 13
  • 17
  • The only problem I encountered while using super __init__ approach is, it doesn't return me the instance of parent class. Thus in case a 3rd parameter is deduced based on name and year inside the parent init method, child object doesn't get access to that 3rd parameter as__init__ doesn't return it. So I prefer calling Person(name, year) from Instructor – Always a newComer Apr 23 '19 at 06:28
  • 4
    There is no "instance of parent class". There is only one instance, it is the one that is being initialized, and usually it is called "self". – nagylzs Jan 07 '22 at 08:43
  • @AlwaysanewComer Then you did not call the superclass constructor at all (not explicitly at least) but instantiated a new object from the superclass instead. – Come get some Jul 15 '22 at 12:56