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.
Calling a parent constructor within a child class executes the operations of the parent class constructor in the child class.
To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
php class grandpa{ public function __construct(){ echo "I am in Tutorials Point". "\n"; } } class papa extends grandpa{ public function __construct(){ parent::__construct(); echo "I am not in Tutorials Point"; } } $obj = new papa(); ?>
Python recommends using super()
.
Python 2:
super(Instructor, self).__init__(name, year)
Python 3:
super().__init__(name, year)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With