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。
以上就是Python 中 AttributeError 错误:为什么 TestEmployee 对象没有 employee 属性?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号