Python:在一个函数中定义的变量在另一个函数中无法识别

时间:2017-07-28 20:41:19

标签: python function

class TestUM(unittest.TestCase):
    def test_Dynasty_init(self):
        try:
            self.p = ModelInterface(r"E:\HIL\07_Tests\AT_Dynasty_models\AT745\RTM_AT_745.dml") #any dml file should do here
        except Exception:
            self.fail("Dynasty initialization raised ExceptionType unexpectedly!")

    def test_Dynasty_check(self):
        self.p.check()

在第9行,我收到以下错误:

"AttributeError: 'TestUM' object has no attribute 'p'"

我不明白。 self.p功能无法识别test_Dynasty_check

2 个答案:

答案 0 :(得分:3)

您应该使用setUp()tearDown()作为初始化/销毁代码。

如果我没记错的话,unittest库按字母顺序运行以test开头的所有函数。这意味着test_Dynasty_checktest_Dynasty_init之前运行。 编辑:顺序无关紧要,因为每个测试都将从TestCase类的 new 实例运行。

答案 1 :(得分:0)

这可能取决于test_Dynasty_init()是否在类实例的test_Dynasty_check()之前实际调用。