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
.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
- Add a constructor to
Manager
that acceptsname
,salary
(default value of50000
), andproject
(default value ofNone
). - Inside the
Manager
constructor, call the constructor of theEmployee
class providing the three arguments defined in the constructor of the parent class. - Use
self
to assign the relevant attribute to theproject
argument.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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)