IniziaInizia gratis

Customize a subclass

Inheritance is powerful because it allows us to reuse and customize code without rewriting existing code. By calling methods of the parent class within the child class, we reuse all the code in those methods, making our code concise and manageable.

In this exercise, you'll continue working with the Manager class that is inherited from the Employee class. You'll add a constructor that builds on the Employee constructor, taking an additional argument where you can specify the project that the manager is working on.

A simplified version of the Employee class, as well as the beginning of the Manager class you previously created, has been provided for you in script.py.

Questo esercizio fa parte del corso

Introduction to Object-Oriented Programming in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Add a constructor to Manager that accepts name, salary (default value of 50000), and project (default value of None).
  • Inside the Manager constructor, call the constructor of the Employee class providing the three arguments defined in the constructor of the parent class.
  • Use self to assign the relevant attribute to the project argument.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

class Employee:
  def __init__(self, name, salary=30000):
    self.name = name
    self.salary = salary

  def give_raise(self, amount):
    self.salary += amount

class Manager(Employee):
  # Add a constructor 
  def __init__(self, name, ____=____, ____=____):
    
    # Call the parent's constructor   
    ____.____(____, ____, salary)
    
    # Assign project attribute
    ____.____ = ____

  def display(self):
    print("Manager ", self.name)
Modifica ed esegui il codice