Python中的属性错误

2024-09-30 20:24:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向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

但是,每当我调用self_test()时,我总是得到"AttributeError: class Boy has no attribute 'BoyTest'"。为什么?在


Tags: 对象runtestselfhello属性defargs
2条回答

正如亚历克斯所说,你试图用“男孩测试”作为“男孩”的装束:

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

注意变化:

^{pr2}$

收件人:

suite.addTest(loader.loadTestsFromTestCase(BoyTest))

这能解决你的问题吗?在

作为loadTestsFromTestCase的参数,您试图访问Boy.BoyTest,即类对象BoyBoyTest属性,正如错误消息告诉您的那样,该属性不存在。你为什么不直接用BoyTest代替呢?在

相关问题 更多 >