Bill Kariri
Bill Kariri

Reputation: 81

Error when trying to access a class attribute

I am trying to run this code and getting an error

This is the code:

# File oop.py
class Person():

  def __init__(self, name, job=None, pay=0):
    self.name = name
    self.job = job
    self.pay = pay

    def firstname(self):
      return self.name.split()[0]

    def lastname(self):
      return self.name.split()[-1]

    def giveRaise(self,percent):
      self.pay = int(self.pay * (1 + percent))

class Manager(Person):

  def __init__(self, name, pay):
    Person.__init__(self, name, 'mgr', pay)

  def giveRaise(self, percent, bonus = .10):
    Person.giveRaise(self, percent + bonus)

if __name__ == '__main__':
  #self-test code
  chris = Manager('Chris Jones', 50000)
  chris.giveRaise(.20)
  print(chris)

This is the exact error I am getting. I have no Idea what's wrong with my code. Please help me solve it.

Traceback (most recent call last):
  File "main.py", line 29, in <module>
    chris.giveRaise(.20)
  File "main.py", line 24, in giveRaise
    Person.giveRaise(self, percent + bonus)
AttributeError: class Person has no attribute 'giveRaise'

Upvotes: 0

Views: 223

Answers (1)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

It is happening because of the Person.__init__ indent. python assumes that all of firstname,lastname and giveRaise as a local function of __init__ function. (You define them in that function). so fix your indention like this:

class Person:

    def __init__(self, name, job=None, pay=0):
        self.name = name
        self.job = job
        self.pay = pay

    def firstname(self):
        return self.name.split()[0]

    def lastname(self):
        return self.name.split()[-1]

    def giveRaise(self,percent):
        self.pay = int(self.pay * (1 + percent))


class Manager(Person):

    def __init__(self, name, pay):
        Person.__init__(self, name, 'mgr', pay)

    def giveRaise(self, percent, bonus = .10):
        Person.giveRaise(self, percent + bonus)


if __name__ == '__main__':
    chris = Manager('Chris Jones', 50000)
    chris.giveRaise(.20)
    print(chris.pay)

You code gonna work. Note that it is better to use super instead of Person, like this:

class Manager(Person):

    def __init__(self, name, pay):
        super(Manager, self).__init__(name, 'mgr', pay)

    def giveRaise(self, percent, bonus = .10):
        super(Manager, self).giveRaise(percent + bonus)

Upvotes: 2

Related Questions