What does it mean to override a method?

Question

What does it mean to override a method?

Answer

The point of overriding is to allow different behavior from the same function in different classes.
In our Employee and PartTimeEmployee example, we want both employees to be paid, so we create a method to calculate their wages. And since a part time employee is definitely a type of Employee, it makes sense for them to derive a lot of the same functionality.
However! That doesn’t mean their pay should be calculated in the same way. So we override the calculate_wage method to behave as we want it to for PartTimeEmployee objects.
By defining a method with the same name as found in the base class, Employee, we are overriding the functionality so that any PartTimeEmployees will have their wages calculated appropriately.

2 Likes
class Employee(object):
  """Models real-life employees!"""
  def __init__(self, employee_name):
    self.employee_name = employee_name

  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
  def calculate_wage(self, hours):
    self.hours = hours
    return hours * 12.00

This is the code for the override exercise. There is something I don’t really understand, hope someone can help. It’s the self.hours = hours line. I don’t understand its purpose. I deleted both of them and the code worked just fine.

1 Like

If we create an instance of Employee directly, they will have a wage of 20 dollars an hour. To override this in classes that inherit from Employee, we have a method that will shadow the inherited method, thereby controlling data, such as hourly wage.

1 Like

I think this answer misses some crucial points. First of all, as you can see, hours is not initialized in init. We can pass it along to calculate_wage without using self.hours = hours perfectly fine! Also, if we passed hours to a PartTimeEmployee instance without self.hours, it would calculate the correct wage. What happens, though, in both instances is that the variable hours is added to the instance. Therefore, after using instance.calculate_wage(24), you can retrieve the value of hours using instance.hours! If you leave out these lines, the info will not be available.

5 Likes

Can you provide an example code that represents what you’re saying so I can visualize this? I get it a little bit, but an example would further my understanding of what you said.

2 posts were split to a new topic: Why don’t we have init() method in the second class?