amazinz5 amazinz5 - 1 year ago 59
Python Question

'class' object has no attribute 'method'

I'm getting an error "AttributeError: 'Test Employee' object has no attribute 'increment_salary'". Not sure why I'm getting this error because 'increment_salary' is a method, not an attribute and I'm 99% sure I created it correctly. I've searched and the only answers I saw said to check mix of indentation and spaces so I went through and triple checked every indent. It may be wrong here because I am not familiar with how to copy code here but I am sure I did it right in geany.

import unittest

class Employee():
"""stores and updates info for each employee"""
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def update_salary(self, new_salary):
self.salary = new_salary
def increment_salary(self, increase):
self.salary += increase

class TestEmployee(unittest.TestCase):

def setUp(self):
first_name = 'first'
last_name = 'last'
pay_name = 100
self.employee = Employee(first_name, last_name, pay)

def test_update_salary(self):
new_salary = 110
self.assertEqual(self.new_salary, self.update_salary)

def test_raise(self):
increase = 10
self.assertEqual(110, self.increment_salary(increase))


Answer Source

You try to call increment_salary() on your TestEmployee testcase:

self.assertEqual(110, self.increment_salary(increase))

You forgot to call it on self.employee instead. The following would not throw the exception:

self.assertEqual(110, self.employee.increment_salary(increase))

The assertion would fail however because Employee.increment_salary() returns None always. You want to test what the salary attribute is set to in your test:

def test_raise(self):
    increase = 10
    self.assertEqual(110, self.employee.salary)

Note that methods are just attributes too; they are callable attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download