Home > Software engineering >  Reuse constructor parameters in child class
Reuse constructor parameters in child class

Time:03-03

I want to reuse base class Person constructor in Instructor class but add additional parameter degree. Somehow it doesn't work. Please check further info:

class Person(object):
    def __init__(self, name = 'Jane Doe', year = 2000):
        self.n = name
        self.y = year
        
class Instructor(Person):
    def __init__(self, name, year, degree=12):
         super().__init__(name, year) #call base class ctor
         self.degree = degree;    

Neveretheless when i do this:

sammy = Instructor("John") # i want to set John as name

I am getting following error:

Exception has occured: TypeError __init__() missing 1 required positional arguments year 

Since year & degree having default values i do not understand the error.

CodePudding user response:

As the comment suggests, you have to set default value for Instructor's init. While you are creating an object of Instructor the Instructor's constructor is called before the Person's constructor. So it doesn't care about default values in the Person's constructor.

class Person(object):
    def __init__(self, name = 'Jane Doe', year = 2000):
        self.n = name
        self.y = year
        
class Instructor(Person):
    def __init__(self, name = 'Jane Doe', year = 2000, degree=12):
         super().__init__(name, year) #call base class ctor
         self.degree = degree; 

And then:

sammy = Instructor("John")

runs without exception.

CodePudding user response:

The first __init__ that runs is the Instructor's init. That's why you get the error. Setting a default value for year will run without exception.

  • Related