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
Istruzioni dell'esercizio
- Add a constructor to
Managerthat acceptsname,salary(default value of50000), andproject(default value ofNone). - Inside the
Managerconstructor, call the constructor of theEmployeeclass providing the three arguments defined in the constructor of the parent class. - Use
selfto assign the relevant attribute to theprojectargument.
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)