Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a parent class constructor from a child class in python [duplicate]

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.

like image 790
Daniel Love Jr Avatar asked Sep 24 '12 00:09

Daniel Love Jr


People also ask

Does child class call parent constructor Python?

Calling a parent constructor within a child class executes the operations of the parent class constructor in the child class.

How do we call the constructor of parent class from 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.

How do you call parent constructor in child constructor?

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).

How do you call a constructor of a parent class from a child class explain with example?

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(); ?>


1 Answers

Python recommends using super().

Python 2:

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

Python 3:

super().__init__(name, year) 
like image 71
vinnydiehl Avatar answered Sep 21 '22 16:09

vinnydiehl