
python 中的 attributeerror 问题
在编写一个 python 程序时,可能会遇到 attributeerror。该错误表明尝试访问或操作对象中不存在的属性。
问题
以下代码展示了 employee.py 文件和主代码:
立即学习“Python免费学习笔记(深入)”;
# employee.py
class employee():
def __init__(self, first_name, last_name, pay):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.pay = pay
def give_raise(self, pay_raise=5000):
self.pay += pay_raise
# 主代码
import unittest
from employee import employee
class testemployee(unittest.testcase):
def setup(self):
self.employee = employee('taylor', 'swift', 20000)
def test_give_default_raise(self):
self.employee.give_raise()
self.assertequal(self.self.pay, 25000)
unittest.main()运行此代码后,会出现以下错误:
attributeerror: 'testemployee' object has no attribute 'employee'
解决方法
该错误是由于拼写错误造成的。setup 方法应更正为 setup,如下所示:
class TestEmployee(unittest.TestCase):
def setUp(self):
self.employee = Employee('taylor', 'swift', 20000)更正拼写后,代码应该可以正常运行,并且不会出现 attributeerror。










