使用闭包创建Python类方法
我第一次使用了使用闭包创建Python类方法,python,closures,class-method,Python,Closures,Class Method,我第一次使用了unittest模块(因为我对Python非常陌生),我发现自己一遍又一遍地执行相同的测试断言。我想把代码拉到一个公共函数中,但是unittest断言是TestCase的方法(即self.assertTrue)。我试图在每个为我执行断言的TestCase中使用闭包来构造类方法。例如: def _keys_in_dict_asserter(cls): """ A simple closure that creates an "assert keys in dict"
unittest
模块(因为我对Python非常陌生),我发现自己一遍又一遍地执行相同的测试断言。我想把代码拉到一个公共函数中,但是unittest
断言是TestCase
的方法(即self.assertTrue
)。我试图在每个为我执行断言的TestCase
中使用闭包来构造类方法。例如:
def _keys_in_dict_asserter(cls):
"""
A simple closure that creates an "assert keys in dict" function for each TestCase
"""
def cls_asserter(dictionary, *args):
for key in args:
cls.assertTrue(key in dictionary)
return cls_asserter
class TestFunctionUnderTest(TestCase):
# I want to create an asserter function as a class method using this
# class object. Python won't let me. Why?
@classmethod
keys_in_dict = _keys_in_dict_asserter(cls)
def test_returned_dict_contains_expected_items(self):
"""
Make sure the dict returned has all the keys expected by the caller under normal operation
"""
keys_in_dict(function_under_test())
不过,我不知道如何正确地写这个。帮助?一个简单的私有方法怎么样?或者是一个简单的函数,它作为参数传递
self
?是的,为什么不把它变成一个方法呢?如果函数名不是以“test”开头,它将不会被解释为一个函数名。我是从这种方法开始的,但是每个测试类都需要它自己的方法副本。它不能在这些类之外实现,因为它必须使用self
来调用assert*()
方法。也许我可以创建一个从TestCase继承的虚拟类来公开该方法?你的代码没有意义<代码>目录中的键=\u目录中的键(cls)目录中的键从何而来?我真的不明白你为什么不能这么做:@classmethod;def keys_in_dict(cls,dictionary,*args):…
没有包装器\u keys_in_dict_asserter
为什么不直接继承TestCase
,在子类中添加keys_in_dict_asserter
作为一种方法,并从该子类继承测试?简单的私有方法如何?或者是一个简单的函数,它作为参数传递self
?是的,为什么不把它变成一个方法呢?如果函数名不是以“test”开头,它将不会被解释为一个函数名。我是从这种方法开始的,但是每个测试类都需要它自己的方法副本。它不能在这些类之外实现,因为它必须使用self
来调用assert*()
方法。也许我可以创建一个从TestCase继承的虚拟类来公开该方法?你的代码没有意义<代码>目录中的键=\u目录中的键(cls)目录中的键从何而来?我真的不明白你为什么不能这么做:@classmethod;def keys_in_dict(cls,dictionary,*args):…
没有包装器\u keys_in_dict_asserter
为什么不直接继承TestCase
,在子类中添加keys_in_dict_asserter
作为方法并从该子类继承测试?