Arin Ekandem
Arin Ekandem

Reputation: 107

How to utilize class inheritance?

Trying to understand inheritance. The PartTimeEmployee class should inherit attributes from the Employee class. But I get errors trying "tap" into the ReturnName method to print out the PartTimeEmployee information.

class Employee(object):
    def __init__(self, employee_name):
        self.employee_name = employee_name

    def ReturnName(self, employee_name):
        self.employee_name = employee_name
        return employee_name

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


class PartTimeEmployee(Employee):
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 12.00

ft_emp = Employee("Mike")
ft_emp_name = ft_emp.ReturnName("Mike")

pt_emp = PartTimeEmployee("Bill")
#pt_emp_name = pt_emp.ReturnName("Bill")

ft_pay = ft_emp.calculate_wage(40)
#pt_pay = pt_emp_name.calculate_wage(20)

print "Full time employee %s made $%d for the week." %(ft_emp_name, ft_pay)
#print "Part time employee %s made $%d for the week." %(pt_emp_name, pt_pay)

>>>
Full time employee Mike made $800 for the week.

Upvotes: 0

Views: 70

Answers (2)

chepner
chepner

Reputation: 530970

What you really have are two different kinds of employees, full-time and part-time. As such, I might use a design like this:

class Employee(object):
    def __init__(self, name, wage):
        self.name = name
        self.wage = wage

    def calculate_wage(self, hours):
        return hours * self.wage


class FullTimeEmployee(Employee):
    def __init__(self, name):
        super().__init__(name, 20)


class PartTimeEmployee(Employee):
    def __init__(self, name):
        super().__init__(name, 12)

Employee contains everything that is common to either type of employee. The subclasses contain information specific to each type, so far just the hourly wage paid each. Notice there is no ReturnName method. If you want an employee's name, just access the name attribute directly.

ft_emp = FullTimeEmployee("Mike")
ft_emp_name = ft_emp.name

pt_emp = PartTimeEmployee("Bill")
pt_emp_name = pt_emp.name

ft_pay = ft_emp.calculate_wage(40)
pt_pay = pt_emp.calculate_wage(20)

print "Full time employee %s made $%d for the week." %(ft_emp_name, ft_pay)
print "Part time employee %s made $%d for the week." %(pt_emp_name, pt_pay)

Upvotes: 1

piokuc
piokuc

Reputation: 26164

The commented line:

#pt_pay = pt_emp_name.calculate_wage(20)

should be:

pt_pay = pt_emp.calculate_wage(20)

Otherwise it is an attempt to call method calculate_wage on a string object.

Upvotes: 2

Related Questions