Using self vs cls to access variable in unittest
假设我有一个简单的类对象,它看起来像某种
1 2 3 4 5 | from collections import Counter class Vocabulary: def __init__(self, words): self.vocab = Counter(words) |
将
1 2 3 4 5 6 7 8 9 10 | import unittest class VocabularyTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"]) def test_counts_set_correctly(self): self.assertEqual(cls.vocab["a"], 2) |
号
或者我可以只用
1 2 3 4 5 6 7 | class VocabularyTests(unittest.TestCase): def __init__(self, *args, **kwargs): super(VocabularyTests, self).__init__(*args, **kwargs) self.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"]) def test_counts_set_correctly(self): self.assertEqual(self.vocab["a"], 2) |
以上两种方法都可以。但如果我有一种不和谐的模式呢:
1 2 3 4 5 6 7 8 9 10 | import unittest class VocabularyTests(unittest.TestCase): @classmethod def setUpClass(self): self.vocab = Vocabulary(["z","a","b","c","f","d","e","g","a","d","b","e","w"]) def test_counts_set_correctly(self): self.assertEqual(self.vocab["a"], 2) |
。
根据python类中使用的"cls"变量是什么?,这只是一种编码约定,但是在使用
对于
1 2 | def setUp(self): ... |
如果希望每个测试类执行一次安装程序,请将其放在此处:
1 2 3 | @classmethod def setUpClass(cls): ... |
号
最后,让我们来解决一个误解。技术上来说,这两者没有区别:
1 2 3 | @classmethod def setUpClass(cls): ... |
号
还有这个:
1 2 3 | @classmethod def setUpClass(self): ... |
。
第二种方法只是更混乱/不好地编写第一种方法。