Using inheritance in python

后端 未结 4 1239
轮回少年
轮回少年 2021-01-03 06:36

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 questi

相关标签:
4条回答
  • 2021-01-03 07:13

    Look at the declaration of Executive.__init__:

    def __init__(self, name, wage, yearlyBonus):
    

    Nowhere in there does it declare a variable named salary. But when you call the superclass constructor,

        Employee.__init__(self, name, salary) 
    

    you are asking Python to pass the value of a variable named salary as the third parameter. Python is just complaining that this variable does not exist.

    I imagine you can figure out how to fix it from there. :-)

    0 讨论(0)
  • 2021-01-03 07:17

    Yes, your init function does not have variable named salary, which gives error when you passed it in to Employee.init.

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

    when you do this

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

    which one correlates to the salary? passed that as the employee init method. Better if you call the Employee constructor with super

    Guessing from this method

    def wage(self):
            return self._salary/26   
    

    Maybe this is what you want (not sure how to account yearlyBonus though)

     class Executive(Employee):
            def __init__(self, name, wage, yearlyBonus):
                Employee.__init__(self, name, wage * 26) 
    
    0 讨论(0)
  • 2021-01-03 07:32

    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) 
    
    0 讨论(0)
  • 2021-01-03 07:39

    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.

    0 讨论(0)
提交回复
热议问题