Reputation: 25
Here's my homework assignment:
The first part of the problem is to define the subclass
Worker
that inherits fromEmployee
and includes an attribute that refers to another employee who is the worker's manager. You should define a methodget_manager
that returns the workers' manager.Example:
worker = Worker("Fred", 52000, myboss)
The second part of the problem is to define the subclass
Executive
that inherits fromEmployee
and includes an attribute that refers to the yearly bonus.You should override the wage method to compute executive pay based on his/her salary and bonus. You should use the wage method of
Employee
in the definition of the wage method for theExecutive
class.Example:
executive = Executive("Kerry", 520000, 1040000)
I submitted the following code, but I was told “you got the wrong wage for an executive”. I can't see what the error is. How do I make it right?
class Employee(object):
def __init__(self, name, salary):
self._name = name
self._salary = salary
def my_name(self):
return self._name
def wage(self):
return self._salary/26 # fortnight pay
class Worker(Employee):
def __init__(self, name, salary, manager):
Employee.__init__(self, name, salary)
self._manager = manager
def getManager(self):
return self._manager
class Executive(Employee):
def __init__(self, name, wage, yearlyBonus):
Employee.__init__(self, name, salary)
self._yearlyBonus = yearlyBonus
def wage(self):
return Employee.wage(self)
Upvotes: 1
Views: 1152
Reputation: 20339
The two approaches super(parent, self).method(...)
approach or the parent.method(self,...)
are roughly equivalent. In both cases, it allows you to call a method
from the parent and applies it to the child.
This method can be __init__
: it's always a good idea to initialize a child instance like its parent:
class Worker(Employee):
def __init__(self, *args):
Employee.__init__(self, ...)
finish_the_initialization_of_worker
but the method can be anything, like, wage
class Executive(Employee):
def wage(self):
return Employee.wage(self) + self._yearly_bonus
Upvotes: 0
Reputation: 3830
You can also do use:
class Worker(Employee):
def __init__(self, name, salary, manager):
Employee.__init__(self, name, salary)
self._manager = manager
This will also work on old-style classes, if you happen to inherit one.
Upvotes: 0
Reputation: 122336
You can use super()
to call the superclass of the current class:
def __init__(self, name, salary, manager):
super(Worker, self).__init__(name, salary)
self._manager = manager
Upvotes: 2