使用self和cls访问unittes中的变量

2024-05-19 00:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个简单的类对象,它看起来像某种Counter(当然它还有其他函数,但它超出了这个问题的范围):

from collections import Counter

class Vocabulary:
    def __init__(self, words):
        self.vocab = Counter(words)

Vocabulary类添加到unittest中,我可以使用setUpClass类方法:

^{pr2}$

或者我可以使用self

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)

以上两种方法都可以。但如果我有一种不和谐的模式呢:

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)

根据What is the 'cls' variable used for in Python classes?,这只是一个编码约定,但是使用@classmethod的unittest的第三个版本与前两个惯用测试之间有什么区别吗?在


Tags: 方法importselfinitdefcounterargsunittest
1条回答
网友
1楼 · 发布于 2024-05-19 00:21:47

对于unittest.TestCase子类,不要在__init__中进行任何测试设置。不是为了这个。如果希望每次测试都执行一次设置,请将其放在此处:

def setUp(self):
    ...

如果要在每个测试中执行一次安装程序,请将其放在此处:

^{pr2}$

最后让我们解决一个误解。这两者在技术上没有区别:

^{pr2}$

还有这个:

@classmethod
def setUpClass(self):
    ...

第二种方法只是用一种更令人困惑/更糟糕的方式来写第一种。在

相关问题 更多 >

    热门问题