为什么抱怨变量没有被定义

时间:2018-01-10 14:56:47

标签: python python-2.7 python-unittest

我是编写python测试代码的新手,目前正在尝试使用unittest。

为什么抱怨:

class MyTestClass(unittest.TestCase):
    testdata = "somefile.json"
    def testparse(self):
        data = json.loads(open(testdata).read())


Traceback (most recent call last):
  File "test.py", line 14, in test_instantiation
    data = json.loads(open(testdata).read())
NameError: global name 'testdata' is not defined

2 个答案:

答案 0 :(得分:1)

因为变量testdata被定义为CLASS VARIABLE,所以它不是任何函数的局部变量。引用这样的变量使用类命名空间(MyTestClass.testdata)。

在这里,您可以了解Python中的类变量:Static class variables in Python

也许使用实例变量?实例变量应该在某个方法中定义(理想情况下是构造函数)。

如果你想要本地(方法)变量,在你想要使用它的函数中定义它,不要使用任何前缀 - classname或self。

答案 1 :(得分:0)

试试这个:

class MyTestClass(unittest.TestCase):
    def __init__(self):
        self.testdata = "somefile.json"
    def testparse(self):
        data = json.loads(open(self.testdata).read())

这样,testdate成为公共财产 如果你想私有使用@Wax Cage的解决方案