Python中的属性错误

时间:2009-08-27 04:28:58

标签: python attributeerror

我正在尝试在Python中为对象添加unittest属性

class Boy:

    def run(self, args):
        print("Hello")

class BoyTest(unittest.TestCase)

    def test(self)
         self.assertEqual('2' , '2')

def self_test():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest))
    return suite

但是,每当我致电"AttributeError: class Boy has no attribute 'BoyTest'"时,我都会收到self_test()。为什么呢?

2 个答案:

答案 0 :(得分:3)

作为loadTestsFromTestCase的参数,您尝试访问Boy.BoyTest,即类对象BoyTest的{​​{1}}属性,它不存在,正如错误消息告诉你的那样。你为什么不在那里使用Boy

答案 1 :(得分:-1)

正如亚历克斯所说,你正在尝试使用BoyTest作为男孩的属性:

class Boy:

    def run(self, args):
        print("Hello")

class BoyTest(unittest.TestCase)

    def test(self)
         self.assertEqual('2' , '2')

def self_test():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(BoyTest))
    return suite

请注意更改:

suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest))

为:

suite.addTest(loader.loadTestsFromTestCase(BoyTest))

这会解决您的问题吗?