Python 为什么它抱怨没有定义变量
我刚开始编写python测试代码,目前正在尝试unittest 这是为什么抱怨:Python 为什么它抱怨没有定义变量,python,python-2.7,python-unittest,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
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
试试这个:
class MyTestClass(unittest.TestCase):
def __init__(self):
self.testdata = "somefile.json"
def testparse(self):
data = json.loads(open(self.testdata).read())
这样testdate就变成了一个公共属性
如果您想将其保留为私有,请使用@Wax-Cage的解决方案,因为变量testdata被定义为类变量,它不是任何函数的局部变量。要引用此类变量,请使用类名称空间(MyTestClass.testdata) 在这里,您可以了解Python中的类变量: 也许使用实例变量?实例变量应该在某个方法中定义(理想情况下是构造函数)
如果需要局部(方法)变量,请在要使用它的函数中定义它,不要使用任何前缀-classname或self。
'testdata'!='测试文件“
。同样是的,这是一个类属性而不是一个全局变量。请接受我的回答…unittest.TestCase.\uuuu init\uuuu
存在并且不应该被覆盖,您完全破坏了测试。您应该改用setUp()
方法。这里不需要这样做,class属性很好,不需要移动到实例属性。