Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inheritance in python

this is my homework assignment, I saw it posted on the website before, but it looks like it was unsolved and I got a different error message than a person asking that question before.

the first part of the problem is to define the subclass Worker that inherits from Employee and includes an attribute that refers to another employee who is the worker's manager. You should define a method get_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 from Employee 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 the Executive class.

Example:

executive = Executive("Kerry", 520000, 1040000)

My code is written below and the error message I get is: 'global name 'salary' is not defined' in the line 'Employee.init(self, name, salary) ' for class Executive (It works for Worker class). Why do I get that error and how can I fix it?

Thank you for your help!

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)
like image 448
kate88 Avatar asked Dec 02 '22 23:12

kate88


2 Answers

The error is pretty clear. salary is not defined in the __init__ method of Executive.

You used wage as an argument to __init__, but salary when calling __init__ of your parent class, so you should stick to one variable name:

class Executive(Employee):
    def __init__(self, name, salary, yearlyBonus):
        Employee.__init__(self, name, salary) 

Also, you can get around typing all of those parameters in each time by using *args:

class Executive(Employee):
    def __init__(self, *args, yearlyBonus):
        super(Executive, self).__init__(*args)

Use super() instead of calling the parent class's __init__ method. It makes multiple inheritance a bit easier.

like image 197
Blender Avatar answered Dec 09 '22 16:12

Blender


Just look at the code where the error is occurring, and keep looking until you notice what doesn't match up:

def __init__(self, name, wage, yearlyBonus):
    Employee.__init__(self, name, salary) 
like image 44
John Zwinck Avatar answered Dec 09 '22 15:12

John Zwinck