使用VisualStudio在python中开发时TestClass中的变量

时间:2016-07-18 22:26:17

标签: python visual-studio unit-testing tdd

我正在学习使用visual studio在python中开发。我正在实施一个测试类。我坚持的事情是应该在多个测试中使用的变量声明在哪里。例如,在下面的代码中应该声明calc。

 class Test_test1(unittest.TestCase): 

    def test_add_method(self):
        calc = Calculator()
        #more code

    def test_subtract(self):
        calc = Calculator()
        #more code

1 个答案:

答案 0 :(得分:0)

在类级别的范围内,而不是在函数的范围内。

在下面的python示例中,您可以看到如何定义两者:

def scope_test():
def do_local():
    spam = "local spam"

def do_nonlocal():
    nonlocal spam
    spam = "nonlocal spam"

def do_global():
    global spam
    spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

输出是:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam