Python 中 AttributeError 错误:为什么 TestEmployee 对象没有 employee 属性?
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

python 中的 attributeerror 问题
在编写一个 python 程序时,可能会遇到 attributeerror。该错误表明尝试访问或操作对象中不存在的属性。
问题
以下代码展示了 employee.py 文件和主代码:
# 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 属性?》,希望本文对你有所帮助!关注米云公众号,给大家分享更多文章知识!
