Calling a parent class constructor from a child class in python
Question:
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.
Answers:
Python recommends using super()
.
Python 2:
super(Instructor, self).__init__(name, year)
Python 3:
super().__init__(name, year)
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 recommends using super()
.
Python 2:
super(Instructor, self).__init__(name, year)
Python 3:
super().__init__(name, year)